What is the time.Parse() Function in Golang

Golang time.parse() is a built-in function that parses a formatted string and returns the time value represented by the string. It 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.

Syntax

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

Parameters

  1. layout: It is a layout string specifying the input string’s format.
  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 absent, 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 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

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.

Leave a Comment