Date and Time in Golang with example #4

Date and Time in Golang with example #4

Learn how to work with dates and times in Go with easy-to-follow examples

Play this article

In Go, the time package provides functionality for working with dates and times.

Here is an example of how you can use the time package to get the current time and then format it in a specific way:

package main

import (
    "fmt"
    "time"
)

func main() {
    // Get the current time
    now := time.Now()

    // Format the time according to the layout string
    fmt.Println(now.Format("2006-01-02 15:04:05"))
}

Output:

2023-01-05 14:25:34

The layout string used in the Format method is a reference time, which is Mon Jan 2 15:04:05 MST 2006. The layout string specifies how the reference time should be formatted. In this case, the layout string is:

"2006-01-02 15:04:05"

This layout string formats the time as follows:

  • 2006: the year (4 digits)

  • 01: the month (2 digits, with a leading zero if necessary)

  • 02: the day of the month (2 digits, with a leading zero if necessary)

  • 15: the hour (2 digits, with a leading zero if necessary)

  • 04: the minute (2 digits, with a leading zero if necessary)

  • 05: the second (2 digits, with a leading zero if necessary)

You can use different layout strings to format the time in different ways. For example, the following layout string formats the time as "Monday, January 2, 2006":

"Monday, January 2, 2006"

You can also use the time package to parse a date string and convert it to a time.Time value. Here is an example:

package main

import (
    "fmt"
    "time"
)

func main() {
    // Parse a date string in the format "YYYY-MM-DD"
    dateStr := "2023-01-05"
    t, err := time.Parse("2006-01-02", dateStr)
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println("Parsed date:", t)
}

This will output the parsed date as a time.Time value. For example: "2023-01-05 00:00:00 +0000 UTC"