Go Time Formatting and Manipulation

Go Time Formatting and Manipulation

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

GoJava
2006-01-02yyyy-MM-dd
20060102yyyyMMdd
January 02, 2006MMMM dd, yyyy
02 January 2006dd MMMM yyyy
02-Jan-2006dd-MMM-yyyy
01/02/06MM/dd/yy
01/02/2006MM/dd/yyyy
010206MMddyy
Jan-02-06MMM-dd-yy
Jan-02-2006MMM-dd-yyyy
06yy
MonEEE
MondayEEEE
Jan-06MMM-yy

Time

GoJava
15:04HH:mm
15:04:05HH:mm:ss
3:04 PMK:mm a
03:04:05 PMKK:mm:ss a

DateTime

GoJava
2006-01-02T15:04:05yyyy-MM-dd'T'HH:mm:ss
2006-01-02T15:04:05-0700yyyy-MM-dd'T'HH:mm:ssZ
2 Jan 2006 15:04:05d MMM yyyy HH:mm:ss
2 Jan 2006 15:04d MMM yyyy HH:mm
Mon, 2 Jan 2006 15:04:05 MSTEEE, 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)