Go - Parse Date Strings



Parsing Strings into Time in Golang

In Golang, parsing string involves converting a string representation into a specific format as date into a time.Time object. This allows you to perform various date and time operations, such as formatting, arithmetic, and comparisons.

Using the Parse Function

Here, we can use the Parse function that is provided by the time package, and 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 of Parse() Function

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: Parsing a Custom Date-Time Format

In this example, we parses the string 'v' representing a date-time according to the layout 'l' into a 'time.Time' object 'tt'. The parsed date-time value is printed. Errors during parsing are ignored.

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: Parsing an RFC3339 Date-Time String

In this example, we parses the string 'str' representing a date-time in RFC3339 format into a time.Time object 'tt'. If there is an error during parsing, it prints the error; otherwise, it prints the parsed date-time value.

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
Advertisements