How to Use the time.Parse() Function in Golang

Golang time.parse() function is used to parse a formatted string and returns the time value represented by the string.

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 1: How to Use time.Parse() function

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.

Example 2: 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

That’s it.

Related posts

Golang time.Sleep()

Golang time.Clock()

Golang time.Before()

Golang time.After()

Golang time.Tick()

2 thoughts on “How to Use the time.Parse() Function in Golang”

  1. I don’t understand – Why?!!

    With this: layout = “2006-01-02 14:04:05” – OK
    and with this: layout = “2006-01-02 15:04:05” – Error

    Reply

Leave a Comment