I recently started working on a project that requires you to do a bit of time formattings and manipulations. This is just my notes on time formatting and manipulations so I can just quickly refer to this note when, you know, I need some reference.
To get current time:
t := time.Now()
Getting current time, with timezone:
t := time.Now().UTC() # UTC timezone example
Getting current time, as unix timestamp:
t := time.Now().Unix()
Time formatting
t.Format(""YOUR_TIME_FORMAT")
Go provides in the time package some constants for commonly used formats:
const {
ANSIC = "Mon Jan _2 15:04:05 2006"
UnixDate = "Mon Jan _2 15:04:05 MST 2006"
RubyDate = "Mon Jan 02 15:04:05 -0700 2006"
RFC822 = "02 Jan 06 15:04 MST"
RFC822Z = "02 Jan 06 15:04 -0700"
RFC850 = "Monday, 02-Jan-06 15:04:05 MST"
RFC1123 = "Mon, 02 Jan 2006 15:04:05 MST"
RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700"
RFC3339 = "2006-01-02T15:04:05Z07:00"
RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
Kitchen = "3:04PM"
// Handy time stamps.
Stamp = "Jan _2 15:04:05"
StampMilli = "Jan _2 15:04:05.000"
StampMicro = "Jan _2 15:04:05.000000"
StampNano = "Jan _2 15:04:05.000000000"
}
Details here : golang.org/pkg/time/#pkg-constants
Common time layouts
Common time layouts with it's other language counterparts
Date
Go | Java |
2006-01-02 | yyyy-MM-dd |
20060102 | yyyyMMdd |
January 02, 2006 | MMMM dd, yyyy |
02 January 2006 | dd MMMM yyyy |
02-Jan-2006 | dd-MMM-yyyy |
01/02/06 | MM/dd/yy |
01/02/2006 | MM/dd/yyyy |
010206 | MMddyy |
Jan-02-06 | MMM-dd-yy |
Jan-02-2006 | MMM-dd-yyyy |
06 | yy |
Mon | EEE |
Monday | EEEE |
Jan-06 | MMM-yy |
Time
Go | Java |
15:04 | HH:mm |
15:04:05 | HH:mm:ss |
3:04 PM | K:mm a |
03:04:05 PM | KK:mm:ss a |
DateTime
Go | Java |
2006-01-02T15:04:05 | yyyy-MM-dd'T'HH:mm:ss |
2006-01-02T15:04:05-0700 | yyyy-MM-dd'T'HH:mm:ssZ |
2 Jan 2006 15:04:05 | d MMM yyyy HH:mm:ss |
2 Jan 2006 15:04 | d MMM yyyy HH:mm |
Mon, 2 Jan 2006 15:04:05 MST | EEE, d MMM yyyy HH:mm:ss z |
Manipulations
You can play around with the time.Time object, be it adding, subtracting, etc
Build a time object using time.Date() Function signature:
func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
Example:
t := time.Date(2019, 11, 7, 20, 34, 58, 651387237, time.UTC)
You can fetch the year, month, and date from a time object by calling it's Date() method. For example
timeNow := time.Now().UTC()
year, month, date := timeNow.Date()
Want to get the first or last day of current month? You can use the time.Date() function to construct the wanted date
timeNow := time.Now().UTC()
year, month, date := timeNow.Date()
firstDayOfMonth := time.Date(year, month, 1, 0, 0, 0, 0, time.UTC)