Time Formatting in Go
Golang Concepts
Go: Time Formatting
Go's time package provides functionality for working with dates and times, including formatting dates and times as strings. The package includes a Time type representing a point in time, and methods for formatting Time values as strings using a layout string.
The layout string specifies the format for the date and time representation. The format uses a reference time of January 2, 2006, at 3:04 PM (MST)
, which can be remembered as 1/2 3:04 PM
.
How to format a Time value as a string using a layout string in Go?
Here's an example of how to format a Time value as a string using a layout string:
package main
import (
"fmt"
"time"
)
func main() {
timeObj := time.Now()
formattedTime := timeObj.Format("2006-01-02 15:04:05 MST")
fmt.Println(formattedTime) // Output: 2023-03-13 15:23:45 UTC
}
In this example, the time.Now() function is used to get the current time as a Time value. The Time.Format() method is then used to format the Time value as a string using the layout string 2006-01-02 15:04:05 MST
.
This layout string specifies the order and format of the year
, month
, day
, hour
, minute
, second
, and timezone
components.
Commonly used formatting codes for the Time.Format() method:
Code | Description |
---|---|
2006 | Year in four digits |
01 | Month as two digits |
Jan | Month as abbreviated name |
January | Month as full name |
02 | Day of month as two digits |
Mon | Weekday as abbreviated name |
Monday | Weekday as full name |
15 | Hour (24-hour clock) as two digits |
03 | Hour (12-hour clock) as two digits |
PM | AM/PM marker |
04 | Minute as two digits |
05 | Second as two digits |
000000 | Microseconds as six digits |
MST | Timezone abbreviation |
-0700 | Timezone offset from UTC as -0700 (or +0500 ) |
-07 | Timezone offset from UTC as -07 (or +05 ) |
You can use any combination of these codes to create your own custom layout string for formatting dates and times.