Incorrect formatting of Date and Time


(Altu Faltu) #1

Not sure what I am missing.
Operation is simple : Format the current time to a specific format.
Want to use the format -

yyyy.MM.dd’T’HH:mm:ss.SSS

fmt.Println(time.Now().Format("2018.07.08T12:00:00.123"))

Output is coming as 
10118.07.08T1110:00:00.111011

https://play.golang.org/p/rWSnO2cYFfl


(Sean Killian) #2

The string that you pass into Format needs to be a specific value: 2006-01-02 03:04:05 PM (UTC-7). Notice how you see all the numbers between 1 and 7 in there. The way you define a format in Go is to write that specific date in the format you want to see your actual time value formatted into. In your case, I think you want it to be: "2006.01.02T15:04:05".


(Altu Faltu) #3

Thanks @skillian . What I donot understand is how is your format and my format different? Except the millisecond part at the end.

However I figured out that go playground has issues with time.


(Sean Killian) #4

The difference is that you used the date 2018-07-08 but it must be the specific date 2006-01-02. Those are magic numbers that Go uses to determine where it should format the year, month and day, respectively.


(Altu Faltu) #5

oh! That was some learning.
Another question how to restrict the milisecond to only 2-3 digits within the formatter? Is there any way?


(Sean Killian) #6

I’m not sure how to do that or if it can be done.