Time Formatting in Go

Go: Time Formatting

Go's time package provides functionality for working with dates and times, including formatting dates and times as strings. The package includes a Time type representing a point in time, and methods for formatting Time values as strings using a layout string.

The layout string specifies the format for the date and time representation. The format uses a reference time of January 2, 2006, at 3:04 PM (MST), which can be remembered as 1/2 3:04 PM.

How to format a Time value as a string using a layout string in Go?

Here's an example of how to format a Time value as a string using a layout string:


    package main

    import (
        "fmt"
        "time"
    )

    func main() {
        timeObj := time.Now()
        formattedTime := timeObj.Format("2006-01-02 15:04:05 MST")
        fmt.Println(formattedTime) // Output: 2023-03-13 15:23:45 UTC
    }

In this example, the time.Now() function is used to get the current time as a Time value. The Time.Format() method is then used to format the Time value as a string using the layout string 2006-01-02 15:04:05 MST.

This layout string specifies the order and format of the year, month, day, hour, minute, second, and timezone components.

Commonly used formatting codes for the Time.Format() method:

CodeDescription
2006Year in four digits
01Month as two digits
JanMonth as abbreviated name
JanuaryMonth as full name
02Day of month as two digits
MonWeekday as abbreviated name
MondayWeekday as full name
15Hour (24-hour clock) as two digits
03Hour (12-hour clock) as two digits
PMAM/PM marker
04Minute as two digits
05Second as two digits
000000Microseconds as six digits
MSTTimezone abbreviation
-0700Timezone offset from UTC as -0700 (or +0500)
-07Timezone offset from UTC as -07 (or +05)

You can use any combination of these codes to create your own custom layout string for formatting dates and times.

Previous Article