How to Convert Time to String in Go
-
Display Current Time Using
time.Now
in Go -
Convert Time to String Using the
time.Time.String()
Function in Go
Datetime is a type that represents the attributes of a date and time at a certain point in time. Datetime is located in the time
package in Go.
The time
package includes all of the tools you’ll need to tell, measure, and show the time. The fundamental methods to format, parse, display, and modify date and time are also included in the time
package.
time.Time
is the type of any variable or field in a struct that holds time as a value. Time is a unit of measurement that represents a nanosecond in time.
Let’s have a look at some of the following examples.
Display Current Time Using time.Now
in Go
Time is necessary for this program. The current local time is obtained as a time using the new function from the time
package.
The currentTime
variable is used to store the value of time. The fmt.Println
is used to print the current time using the currentTime.String()
output as string format.
package main
import (
"fmt"
"time"
)
func main() {
currentTime := time.Now()
fmt.Println("The time is", currentTime.String())
}
Output:
The time is 2022-03-28 03:45:32 +0000 UTC m=+0.000000001
Convert Time to String Using the time.Time.String()
Function in Go
In this scenario, time
packages provide functionality for calculating and visualizing time. The time.String()
method in Go is used to return the time that has been prepared using the format string.
Furthermore, this function is included in the time
package.
package main
import (
"fmt"
"time"
)
func main() {
Time := time.Date(2022, 03, 28, 03, 50, 16, 0, time.UTC)
t := Time.String()
fmt.Printf("Time without nanoseconds is: %v\n", t)
}
Output:
Time without nanoseconds is: 2022-03-28 03:50:16 +0000 UTC
Related Article - Go Time
Related Article - Go String
- How to Convert String to Integer Type in Go
- How to Convert an Int Value to String in Go
- How to Parse Date String in Go
- How to Efficiently Concatenate Strings in Go
- How to Write Multiline Strings in Go
- How to Read a File Into String in Go