Go - Format Current Time - custom and predefined formats



The example displays the current time in custom and predefined formats.

Go does not use the typical yyyy-mm-dd format specifier; it uses the following reference DateTime format:

Tue Jun 2 15:04:05 -0700 MST 2021

We format the time how we structure this specific reference DateTime.

Go - Format Current Time - custom and predefined formats

Let's create a file named "go_example.go" and add the following source code to it:


package main

import (
    "fmt"
    "time"
)

func main() {

    now := time.Now()

    fmt.Println("Time: ", now.Format("15:04:05"))
    fmt.Println("Date:", now.Format("Jun 2, 2021"))
    fmt.Println("Timestamp:", now.Format(time.Stamp))
    fmt.Println("ANSIC:", now.Format(time.ANSIC))
    fmt.Println("UnixDate:", now.Format(time.UnixDate))
    fmt.Println("Kitchen:", now.Format(time.Kitchen))
}

Run the following command to execute the go_example.go file:

G:\GoLang\examples>go run go_example.go
Time:  17:19:19
Date: Jun 21, 21216
Timestamp: Jun 21 17:19:19
ANSIC: Mon Jun 21 17:19:19 2021
UnixDate: Mon Jun 21 17:19:19 IST 2021
Kitchen: 5:19PM

Comments