'How to format current time into YYYY-MM-DDTHH:MM:SSZ

Never tried Go before and currently doing a small project. One of the task is to get current system time and represent it in YYYY-MM-DDT00:00:00Z format. I believe that Z means that time is represented in UTC format but when i looked into db, all timestamps are like this i.e., 2011-11-22T15:22:10Z.

So how can i format like this in Go?

Update I was able to format it using following code

t := time.Now()
fmt.Println(t.Format("2006-01-02T15:04:05Z"))

Now the question remains, what Z signifies here. Should i get UTC Time?

Another question, it looks like that the value i am using to format impacts the output i.e., when i used 2019-01-02T15:04:05Z the output became 2029-02-02T20:45:11Z, why?



Solution 1:[1]

Go provides very flexible way to parse the time by example. For this, you have to write the "reference" time in the format of your choice. The reference time is Mon Jan 2 15:04:05 MST 2006. In my case, I used this reference time to parse the Now():

fmt.Println(time.Now().UTC().Format(time.RFC3339))

There are also other reference types if you want to see:

RFC822      = "02 Jan 06 15:04 MST"
RFC822Z     = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
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" // RFC1123 with numeric zone
RFC3339     = "2006-01-02T15:04:05Z07:00"
RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"

Or you can use you desired reference.

Solution 2:[2]

"If a time is in Coordinated Universal Time (UTC), a "Z" is added directly after the time without a separating space. "Z" is the zone designator for the zero UTC offset. "09:30 UTC" is therefore represented as "09:30Z" or "0930Z". Likewise, "14:45:15 UTC" is written as "14:45:15Z" or "144515Z".[16]"

From https://en.wikipedia.org/wiki/Time_zone#UTC

// Some valid layouts are invalid time values for time.Parse, due to formats
// such as _ for space padding and Z for zone information.

and

// Replacing the sign in the format with a Z triggers
// the ISO 8601 behavior of printing Z instead of an
// offset for the UTC zone. Thus:
//  Z0700  Z or ±hhmm
//  Z07:00 Z or ±hh:mm
//  Z07    Z or ±hh

From the source for package time/format.go

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Steve Wilhelm