How to parse Date strings in Golang?

Go ProgrammingServer Side ProgrammingProgramming

When it comes to parsing Date strings in Go, we can use the Parse function that is provided by the time package. In Go, we don't use codes like most other languages to represent the component parts of a date/time string. Instead, Go uses the mnemonic device - standard time as a reference.

For example, the reference time can either look like this −

Mon Jan 2 14:10:05 MST 2020 (MST is GMT-0700)

Or, it can look like this as well.

01/02 03:04:10PM '20 -0700

Syntax

The syntax of the Parse() function is shown below.

func Parse(layout, value string) (Time, error)

The Parse function takes a layout and a value as the arguments and it returns the time and error. The layout is used as a reference and the value is the actual date string that we want to parse.

Example 1

Consider the code that is shown below in which we will use our own defined layout to parse the date.

package main
import (
   "fmt"
   "time"
)
func main() {
   v := "Thu, 05/19/11, 10:47PM"
   l := "Mon, 01/02/06, 03:04PM"
   tt, _ := time.Parse(l, v)
   fmt.Println(tt)
}

Output

If we run the above code with the command 2014-11-12 11:45:26.371 +0000 UTC, then we will get the following output.

2011-05-19 22:47:00 +0000 UTC

Instead of passing a layout of our own, we can also pass a format that the Go time package provide us and it will parse the date as well.

Example 2

Consider the code shown below.

package main
import (
   "fmt"
   "time"
)
func main() {
   str := "2014-11-12T11:45:26.371Z"
   tt, err := time.Parse(time.RFC3339, str)
   if err != nil {
      fmt.Println(err)
   }
   fmt.Println(tt)
}

Output

If we run the above code with the command go run main.go, then we will get the following output.

2014-11-12 11:45:26.371 +0000 UTC
raja
Updated on 22-Feb-2022 05:28:17

Advertisements