Formatting and parsing datetime in Golang

Datetime is a type that contains properties of a date and time at a particular instant. In Go, datetime can be found in the time package. The time package provides the necessary functionality for telling, measuring, and displaying the time. The time package also contains the basic methods to format, parse, display, and manipulate date and time. Any variable or field in a struct that stores time as a value will be of type time.Time, which represents an instant in time with nanosecond precision.

Datetime usually comes in the format YYYY-DD-MM HH:MM:SS with more information like the timezone and monotonic clock reading value formatted as a decimal number of seconds.

2021-09-29 22:14:05.930918675 +0000 UTC m=+0.000073490

The current time

As discussed earlier, you can use the time package to get the date and time. You can use the time.Now method to get the current local time.

// Defines the package name
package main 
import (
  "fmt"
  "time"
)
func main() {
    // current date and time from the time package
    currentTime := time.Now()
    fmt.Printf("The current time is : %v\n", currentTime)
}

Output:

The current time is : 2021-09-30 13:04:45.747781167 +0000 UTC m=+0.000070886

The code snippet above gets the current date and time and prints the result to the standard output.

Note: all methods for manipulating date and time can be found in the time package.

How to format datetime in Go

If you want to format a particular date and time for readability purposes, Go provides a time.Time method, Format, that can be called on a value of type Time. Format is a method that accepts a string layout and transforms the time receiver into a string that follows the specified pattern.

func (t Time) Format(layout string) string
package main
import (
"fmt"
"time"
)
func main() {
current := time.Now()
fmt.Printf("Date Before Format: %v\n", current)
formattedDate := current.Format("January 02, 2006 15:04:05")
fmt.Printf("Date After Format: %v\n", formattedDate)
}

Let’s see what’s happening in the snippet above:

  • Line 1 defines the package name.
  • Lines 2-5 import the time and fmt package.
  • Line 7 time.Now() gets the current datetime, which is a time.Time type and saves the result to variable current.
  • Line 8 prints the current date and time before format to the standard output.
  • Line 10 current.Format formats the current value based on the layout specified and saves the formatted string to variable formattedDate.
  • Line 12 prints the formatted string to the standard output.

Go provides a different format for date and time, as opposed to other programming languages that use the regular yyyy-mm-dd format. Layout is the string format passed as an argument to the Format method.
Go uses the following datetime format:

Mon Jan 2 15:04:05 -0700 MST 2006

There are some predefined layout constants that come with Go. The table below covers a few, but please refer to the Go documentation for the full list

Constant Format Layout
ANSIC “Mon Jan _2 15:04:05 2006”
RFC822 “02 Jan 06 15:04 MST”
RFC1123 “Mon, 02 Jan 2006 15:04:05 MST”
RFC3339 “2006-01-02T15:04:05Z07:00”
Kitchen “3:04PM”
package main
import (
"fmt"
"time"
)
func main() {
date := time.Date(2021, 12, 12, 12, 23, 0, 0, time.Local)
fmt.Printf("Kitchen: %v\n", date.Format(time.Kitchen))
fmt.Printf("RFC1123: %v\n", date.Format(time.RFC1123))
}

Let’s see what’s happening in the snippet above:

  • Line 1 defines the package name.
  • Lines 2-5 import the time and fmt package.
  • Line 7 time.Date creates the corresponding date and time of a given timezone in the given location and saves the result to variable date.
  • Line 8 formats the date value using the kitchen layout and prints the result to the standard output.
  • Line 9 formats the date value based on the RFC1123 layout and prints the result to the standard output.

Below is the function definition for time.Date:

func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time

Note: during conversion, time.Date normalizes the month, day, hour, min, sec, and nsec values when they are specified outside their usual ranges. For example September 31 converts to October 1.

How to parse datetime in Go

Parse is a function that accepts a string layout and a string value as arguments. Parse parses the value using the provided layout and returns the Time object it represents. It returns an error if the string value specified is not a valid datetime. It is important to note that the second argument must be parsable with the specified format in the layout provided as the first argument.

func Parse(layout, value string) (Time, error)
package main
import (
"fmt"
"time"
)
func main() {
parseTime, err := time.Parse("Jan 02, 2006", "Sep 30, 2021")
if err != nil {
panic(err)
}
fmt.Printf("The Parsed time is: %v\n", parseTime)
// using layout RFC1123
parseTime, err = time.Parse(time.RFC1123, "Sun, 12 Dec 2021 12:23:00 UTC")
if err != nil {
panic(err)
}
fmt.Printf("The Parsed time is: %v\n", parseTime)
// the parsed Time can as well be formatted
fmt.Printf("The Formatted Parsed time is: %v", parseTime.Format("02, Jan 2006"))
}

Let’s see what’s happening in the snippet above:

  • Line 8 parses the second argument using the layout specified in the first arguments and saves the corresponding time object to variable parseTime and error to variable err.
  • Lines 9-11 handle the error and panics if there is any.
  • Line 12 prints the parsed time to the standard output.
  • Line 15 parses the second argument using the RFC1123 layout and saves the corresponding time object to variable parseTime.
  • Lines 16-17 handle the error and panics if there is any.
  • Line 18 prints the parsed time to the standard output.
  • Line 22 formats the parsed date and time value using the layout specified and prints the result to the standard output.

The time object returned by parse can be further formatted with the .Format method.

Putting them together

Now, you can format date and time with the Format method using the different layouts and predefined constants provided by Go. You can parse a specific time string based on the specified layout in order to get the corresponding time object using the Parse function.

You can refer to the official Go documentation to read more about other useful time methods.

Free Resources