Convert string to time.Time

Hey there, I got a date and hour like;

050316 = 05:03:16

220902 = September 22, 2002.

How can I convert both date/hour strings 220902 and 050316 to time.Time?

Any help is always appreciated, ty.

Use time.Parse() and create the layout string as follows:

  1. Start from either of these two strings:

    Mon Jan 2 15:04:05 -0700 MST 2006


    01/02 03:04:05PM '06 -0700

    Note the individual values for each element (e.g., “15” for the hour (in 24h format), or “2” for the date). These are used for identifying that particular element in the format string you have to create.

  2. Now pick the elements you need in your format string and create a new string that matches the desired layout:


    to mach the time string, and


    to match the date string from your input values.

See “Constants” in the time documentation for more info.

(And please don’t ask me why the Go team decided against using the international ISO-8601 format as an unambisuous starting point. Everyone who is used to British date formats must always remember that 01/02 in the second format string means month/day and not day/month.)


The end result of Christoph’s advice is:

time.Parse("020106 150405", "220902 050316")

Here’s another walk-through:

1 Like

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