Golang time.Parse() Function

Parsing in programming refers to analyzing and interpreting a string of text. It can help extract information from a text or check if a string of text sticks to a specific format or structure.

This article will show us how to parse a time in Golang.

Golang time Parse

Golang time.parse() function is used to parse a string representation of a date and time and return the corresponding time.Time value. The time.parse() function takes two arguments: a layout string that specifies the format of the input string and the input string that represents the date and time you need to parse.

The Parse() function in the Golang is used to parse a formatted string and then find the time value that it forms.

Syntax

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

Parameters

  1. layout: It is a layout string that specifies the format of the input string.
  2. value: The input string represents the date and time you want to parse.

Return value

The Parse() function returns the time value that it represents. And if a time zone indicator is not present, it returns a time in UTC.

Example

package main

import (
  "fmt"
  "time"
)

const (
  layout = "2006-01-02 15:04:05"
)

func main() {
  dt := "2022-12-13 14:15:16"
  tm, err := time.Parse(layout, dt)
  if err != nil {
    fmt.Println(err)
  }
 fmt.Println(tm)
}

Output

2022-12-13 14:15:16 +0000 UTC

In the above code, the time.Parse() function is used to parse a string representing a date and time in the format “YYYY-MM-DD HH:MM:SS”. The resulting time.Time value is then printed to the console.

Remember that the time.Parse() function can return an error if the input string is not in the correct format.

This is why the code above checks for an error after calling the time.Parse() function, and prints the error if one is returned. It can help you avoid potential issues and ensure that your code works as expected.

Golang Error: Month out of range

The time string is the string representation of the time value to be parsed. It should match the format specified by the layout string.

If the time string is in the correct format, time.Parse will return a time.Time value representing the parsed time.

If the time string is not in the correct format, time.Parse will return an error.

package main

import (
  "fmt"
  "time"
)

const (
  layout = "2006-01-02 14:04:05"
)

func main() {
  dt := "2022-12-13 14:15:16"
  tm, err := time.Parse(layout, dt)
  if err != nil {
    fmt.Println(err)
  }
  fmt.Println(tm)
}

Output

parsing time "2022-12-13 14:15:16": month out of range
0001-01-01 00:00:00 +0000 UTC

Golang time parsing error

Make sure you use the correct format string when parsing the time. Go’s time parsing functions use format strings to specify the layout of the input time string. If the format of the input string doesn’t match the format specified in the format string, it will result in an error.

That’s it for the Golang time.Parse() function.

Leave a Comment