Go for C# developers: Parsing and Formatting time

Time for something that really boggled my mind in the beginning; the choice of how time formats are created in Go.

In most languages you used something like "%Y-%m-%d %H:%M:%S %z" to format time. You might even encounter "YYYY-mm-dd HH:MM:ss zzzz". It should be fairly obvious that we are looking at a "year-month-day hour:minute:seconf timezone" format. The same format in Go is: "2006-01-02 15:04:05 -0700" which actually reads nice and have some logic to it I guess.

However I find the Go time format strings a little confusing to create. And something like "01/02 03:04" always makes me uncertain what it actually is... And a small typo makes it very hard to spot what went wrong as "01/02/06 0700" will look like a date in timezone +7h rather than the correct timezone...

While I can see the logic (if you are used to how time and dates are typically written in the US) in the format string. While I think it would have been more intuitive to use a format like "YYYY-MM-DD hh:mm:ss zzzz" there is always possible to come up with some weird format that requires checking the documentation to get right. For example if MM is month or minutes... But when you think of it the Go format could have been slightly more logical in my opinion. Rather than numbering things based on how US dates are written, how about an approach going from small to big; "2006-05-04 15:02:01 -0700". I think that would have been easier to remember. And if you didn't think about it; 15 is 3pm with a 24h clock...

So while the Go time format is really confusing in the beginning and is easy to get wrong (with typos), it grows on you over time as many things in Go.

For reference: In the Go source you can find the different formats. If you are used to strftime this might be useful.

No comments:

Post a Comment