How to set time to dd-MMM-yyyy HH:mm:ss in go?

11,552

Solution 1

Your layout is incorrect, it should show how the reference time is represented in the format you want, where the reference time is Mon Jan 2 15:04:05 -0700 MST 2006.

Your layout should be:

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

Note the 05 for the seconds part. And since you specified the hours as 15, that is 24-hour format. 3 or 03 is for the 12-hour format.

fmt.Println(time.Now().Format("02-Jan-2006 15:04:05"))

For me it prints:

03-Mar-2016 13:03:10

Also note Jan for months, JAN is not recognized. If you want uppercased month, you may use strings.ToUpper():

fmt.Println(strings.ToUpper(time.Now().Format("02-Mar-2006 15:04:05")))

Output:

03-MAR-2016 13:03:10

Also note that on the Go Playground the time is always set to a constant when your application is started (which is 2009-11-10 23:00:00 +0000 UTC).

Solution 2

fmt.Println(time.Now().Format("02-Jan-2006 15:04:05"))

See Time package constants

The reference time used in the layouts is the specific time:

Mon Jan 2 15:04:05 MST 2006

which is Unix time 1136239445. Since MST is GMT-0700, the reference time can be thought of as

01/02 03:04:05PM '06 -0700

Share:
11,552
Vinay Sawant
Author by

Vinay Sawant

Updated on June 18, 2022

Comments

  • Vinay Sawant
    Vinay Sawant almost 2 years

    https://play.golang.org/p/82QgBdoI2G

    package main
    
    import "fmt"
    import "time"
    
    func main() {
        fmt.Println(time.Now().Format("01-JAN-2006 15:04:00"))
    }
    

    The output should be like if date time today is 2016-03-03 08:00:00 +0000UTC
    Output: 03-MAR-2016 08:00:00
    Time should be in 24hr format.