Incorrect formatting of Date and Time

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
2 Likes

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".

3 Likes

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.

2 Likes

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.

4 Likes

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

2 Likes

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

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.