How to parse date string in Golang?

Total
0
Shares

There is no doubt that Golang creators had their ways of dealing with problems of older languages. They took care of most of the issues which are often neglected. Parsing date is one of them. A new developer might get confused with the notations used to parse date string in Golang. In this article, we will explain the logic behind the layout.

Introduction

According to the date-time format file of golang, instead of using string representations like %Y, %m, %d, %H they have used numeric representation. And the date string used for it is –

January 2, 15:04:05, 2006, in time zone seven hours west of GMT

But why this string? Well, there is a logic. Let’s convert it into numerical form –

January (Month) 01
2 (Date) 02
15 (Hours in 24 format) 03 (Hours in 12 format)
04 (Minutes) 04
05 (Seconds) 05
2006 (year) 06
-0700 (timezone, seven hours west) 07

Now you can see the pattern. It’s continuous progression – 01, 02, 03 …. 07. So,

  • 01 signifies months,
  • 02 signifies date,
  • 03 signifies hours in 12 hour format (use 15 for 24 hours format),
  • 04 signifies minutes,
  • 05 signifies seconds,
  • 06 signifies year in 2 digit format (use 2006 for 4 digits),
  • 07 for timestamp.

Code Example

Suppose we have a date string

Fri, 09/03/21, 10:07PM

Where 09 is the month and 03 is the date.

In order to parse this string and let golang understand the format, we need the layout string like this –

Mon, 01/02/06, 03:04PM

Here 01 signifies month, 02 date, 06 year etc.

Suppose we have a different format for the same string

03-09, 22:07, 2021

Now here we use this format –

date-month, hour:minute, year

So, the equivalent layout string will be –

02-01, 15:04, 2006

We use 15 instead of 03 because the format was 24 hour. Also we used 2006 and not 06 because its yyyy format.

Check out this code –

package main

import (
    "fmt"
    "time"
)

func main() {
    value  := "Fri, 09/03/21, 10:07PM"
    

    layout := "Mon, 01/02/06, 03:04PM"
    t, _ := time.Parse(layout, value)
    fmt.Println(t)
}

    Tweet this to help others

Live Demo

Open Live Demo