212

I'm trying to format the current time using this format yyyyMMddHHmmss.

t := time.Now()
fmt.Println(t.Format("yyyyMMddHHmmss"))

That is outputting:

yyyyMMddHHmmss

Any suggestions?

sergserg
  • 21,716
  • 41
  • 129
  • 182
  • Here's a playground sample of how date formatting works. This is both converting string to time and print out a time in a specific format. https://play.golang.org/p/qK6_9KNJNx – Nitesh Mar 27 '17 at 13:03

6 Answers6

396

Use

fmt.Println(t.Format("20060102150405"))

as Go uses following constants to format date,refer here

const (
    stdLongMonth      = "January"
    stdMonth          = "Jan"
    stdNumMonth       = "1"
    stdZeroMonth      = "01"
    stdLongWeekDay    = "Monday"
    stdWeekDay        = "Mon"
    stdDay            = "2"
    stdUnderDay       = "_2"
    stdZeroDay        = "02"
    stdHour           = "15"
    stdHour12         = "3"
    stdZeroHour12     = "03"
    stdMinute         = "4"
    stdZeroMinute     = "04"
    stdSecond         = "5"
    stdZeroSecond     = "05"
    stdLongYear       = "2006"
    stdYear           = "06"
    stdPM             = "PM"
    stdpm             = "pm"
    stdTZ             = "MST"
    stdISO8601TZ      = "Z0700"  // prints Z for UTC
    stdISO8601ColonTZ = "Z07:00" // prints Z for UTC
    stdNumTZ          = "-0700"  // always numeric
    stdNumShortTZ     = "-07"    // always numeric
    stdNumColonTZ     = "-07:00" // always numeric
    stdFracSecond0    = ".0", ".00" // trailing zeros included
    stdFracSecond9    = ".9", ".99" // trailing zeros omitted
)
MenyT
  • 1,653
  • 1
  • 8
  • 19
Cris
  • 12,799
  • 5
  • 35
  • 50
  • 1
    is it possible to use stdLongYear or stdNumMonth instead of 2006 or 1? – qwertmax Jul 08 '14 at 17:42
  • 118
    acturally the golang format is very strange. why not use the yyyymmddHHiiss style , but use the ""2006/01/02/15/04/05", I have not get it the real reason – Kewin May 10 '16 at 14:32
  • 22
    The layout string is a representation of the time stamp, Jan 2 15:04:05 2006 MST. An easy way to remember this value is that it holds, when presented in this order, the values (lined up with the elements above): 1 2 3 4 5 6 -7 From https://golang.org/src/time/example_test.go – kakilangit Jun 02 '17 at 09:17
  • 78
    Mnemonic technique for those outside the US: figure what you were doing on the 2nd of January of 2006, just five seconds after 15:04, but imagine it happenning in Burkina Faso (UTC -7). Next time you need to format a date, just remember this particular event (!) – Enrico Jun 24 '17 at 22:19
  • am I missing something or there is no way to format with sub-second precision? – aiguy Dec 06 '17 at 22:02
  • 1
    @aiguy - go does support sub-second precision precision by using `.9`, `.99`, ... `.999999`, etc. – jazeee Mar 02 '18 at 18:00
  • 6
    I did not know the sequential mnemonic, handy, but come on why is it not the 1st February... – Silas Davis Aug 10 '18 at 13:08
  • 16
    So all I have to remember, is to line up the date in month-day-year order, then stick the time in the middle of it, and put the timezone after the year, and it becomes super easy to remember. Neat. Anyone got a mnemonic for remembering the order of this mnemonic..? – Joey Sabey Jun 17 '19 at 21:23
  • 34
    @Kewin Agree with you. I am even pissed off by it. The "YYMMDD..." way is perfectly understandable and easy to remember. Look, what the hell is that ---"20060102150405"? What the hell are they thinking? – Zhou Mar 24 '20 at 12:03
  • 4
    Time to write a proper Time function that isn't linked to the backward American style. – Cyberience Jan 08 '21 at 08:13
  • @Zhou There are too many reasons to mention why they do it this way. I prefer it to any other language. Using capital M versus lower case m to distinguish month from minute is error prone. Plus, Go supports at least 4 ways to express month: 1-digit (only 2 if month is double digit), 2-digit (always 2-digits), 3-letter abbreviation (i.e. "Jan") and full month name (i.e. "January"). That's just scratching the surface. There are many more reasons. Trust me, it's better in Go than anywhere else around and no outside libraries needed. – GoForth Dec 22 '21 at 16:51
  • @GoForth any languages out there have all 1-digit, 2-digit, short and long month formats and even more. There's no reason to use numbers like that. What does `2006` mean? June 20th, year 2006 or 20:06 o'clock? OK it's clear in this case, but how about `Z07002`, `-07002`? Non-prefix systems like this is broken. And the order is silly. The ISO 8601 format is much clearer – phuclv Apr 07 '22 at 10:11
  • @phuclv "any languages out there have all 1-digit, 2-digit...". No, they don't. You can't even format dates in JavaScript without a library. For example, in JavaScript I want you to give me a 3-letter abbreviated version of the month of the current time and I want you to do it in one line. In Go it would just be `time.Now().Format("Jan")`. In JavaScript, you would fumble around with regex to come close to that and it would be ugly. How about if I asked for full month name then 2-digit year? Again, in JavaScript it's clumsy. In Go, it's just `time.Now().Format("Jan 06")`. Go wins. – GoForth Apr 08 '22 at 04:52
  • @GoForth JavaScript is just completely broken. Decent languages like C# and all OSes' locale formatting have that feature. In C# it's simply `DateTime.Now.ToString("MMM")` – phuclv Apr 08 '22 at 08:42
  • So a programming language uses a non standard way to represent datetime. Wow, just wow. And I though JavaScript datetime sucks – EternalObserver Jun 30 '23 at 12:03
44

This question comes in top of Google search when you find "golang current time format" so, for all the people that want to use another format, remember that you can always call to:

t := time.Now()

t.Year()

t.Month()

t.Day()

t.Hour()

t.Minute()

t.Second()

For example, to get current date time as "YYYY-MM-DDTHH:MM:SS" (for example 2019-01-22T12:40:55) you can use these methods with fmt.Sprintf:

t := time.Now()
formatted := fmt.Sprintf("%d-%02d-%02dT%02d:%02d:%02d",
        t.Year(), t.Month(), t.Day(),
        t.Hour(), t.Minute(), t.Second())

As always, remember that docs are the best source of learning: https://golang.org/pkg/time/

Luis Cabrera Benito
  • 1,558
  • 13
  • 21
  • This approach doesn't work for 3-letter month representation. `t.Month()` would return `January` and there's no way to convert it to `Jan`. You still need to use `t.Format("Jan")` for this – zbstof Sep 16 '21 at 05:35
  • `t.Month().String()[:3]` can be used for 3 letter month. – shantanoo Feb 08 '23 at 21:39
26

Option 1: Go standard library

t.Format("20060102150405")
Unit Golang Layout Examples Note
Year 06 21, 81, 01
Year 2006 2021, 1981, 0001
Month January January, February, December
Month Jan Jan, Feb, Dec
Month 1 1, 2, 12
Month 01 01, 02, 12
Day Monday Monday, Wednesday, Sunday
Day Mon Mon, Wed, Sun
Day 2 1, 2, 11, 31
Day 02 01, 02, 11, 31 zero padded day of the month
Day _2 ⎵1, ⎵2, 11, 31 space padded day of the month
Day 002 001, 002, 011, 031, 145, 365, 366 zero padded day of the year
Day __2 ⎵⎵1, ⎵⎵2, ⎵11, ⎵31, 365, 366 space padded day of the year
Part of day PM AM, PM
Part of day pm am, pm
Hour 24h 15 00, 01, 12, 23
Hour 12h 3 1, 2, 12
Hour 12h 03 01, 02, 12
Minute 4 0, 4 ,10, 35
Minute 04 00, 04 ,10, 35
Second 5 0, 5, 25
Second 05 00, 05, 25
10-1 to 10-9 s .0 .000000000 .1, .199000000 Trailing zeros included
10-1 to 10-9 s .9 .999999999 .1, .199 Trailing zeros omitted
Time zone MST UTC, MST, CET
Time zone Z07 Z, +08, -05 Z is for UTC
Time zone Z0700 Z, +0800, -0500 Z is for UTC
Time zone Z070000 Z, +080000, -050000 Z is for UTC
Time zone Z07:00 Z, +08:00, -05:00 Z is for UTC
Time zone Z07:00:00 Z, +08:00:00, -05:00:00 Z is for UTC
Time zone -07 +00, +08, -05
Time zone -0700 +0000, +0800, -0500
Time zone -070000 +000000, +080000, -050000
Time zone -07:00 +00:00, +08:00, -05:00
Time zone -07:00:00 +00:00:00, +08:00:00, -05:00:00

In Golang 1.17+ for fraction of seconds (.999 or .000) you can use , instead of . (,999 or ,000) but output is always with .!!! See https://github.com/golang/go/issues/48037

Option 2: strftime Go implementation

import strftime "github.com/itchyny/timefmt-go"
strftime.Format(t, "%Y%m%d%H%M%S")

See for more info

https://github.com/itchyny/timefmt-go

https://linux.die.net/man/3/strftime

MenyT
  • 1,653
  • 1
  • 8
  • 19
  • Thanks for the clarification. So there is no way to get a 24 hour value without 0 padding. Also, choosing 15 instead of 13 for the 24 hour padding is a weird choice. – chmike Apr 27 '22 at 10:00
13
import("time")

layout := "2006-01-02T15:04:05.000Z"
str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(layout, str)
if err != nil {
    fmt.Println(err)
}
fmt.Println(t)

gives:

>> 2014-11-12 11:45:26.371 +0000 UTC
Cool.wen
  • 2,559
  • 1
  • 7
  • 4
  • Thanks for your example, did something similar https://play.golang.org/p/POjXbG1hQWI – Vor Nov 05 '20 at 18:11
8

Time package in Golang has some methods that might be worth looking.

func (Time) Format

func (t Time) Format(layout string) string Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time,

Mon Jan 2 15:04:05 -0700 MST 2006 would be displayed if it were the value; it serves as an example of the desired output. The same display rules will then be applied to the time value. Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard and convenient representations of the reference time. For more information about the formats and the definition of the reference time, see the documentation for ANSIC and the other constants defined by this package.

Source (http://golang.org/pkg/time/#Time.Format)

I also found an example of defining the layout (http://golang.org/src/pkg/time/example_test.go)

func ExampleTime_Format() {
        // layout shows by example how the reference time should be represented.
        const layout = "Jan 2, 2006 at 3:04pm (MST)"
        t := time.Date(2009, time.November, 10, 15, 0, 0, 0, time.Local)
        fmt.Println(t.Format(layout))
        fmt.Println(t.UTC().Format(layout))
        // Output:
    // Nov 10, 2009 at 3:00pm (PST)
        // Nov 10, 2009 at 11:00pm (UTC)
    }
TheZelus
  • 470
  • 6
  • 19
8

Go standard library: time

now := time.Now()
fmt.Println(now) // 2009-11-10 23:00:00 +0000 UTC m=+0.000000001
fmt.Println(now.Format("20060102150405"))
fmt.Println(now.Format("2006/01/02/15/04/05"))
fmt.Println(now.Format("2006-01-02 15:04:05"))
fmt.Println(now.Format("2006-01-02 15:04"))
fmt.Println(now.Format("2006/01/02 15:04:05"))
fmt.Println(now.Format("2006/01/02 15:04:05 (-0700)"))
fmt.Println(now.Format("2006年01月02日 15:04"))
fmt.Println(now.Format(time.Layout))   // 01/02 03:04:05PM '06 -0700
fmt.Println(now.Format(time.ANSIC))    // Mon Jan _2 15:04:05 2006
fmt.Println(now.Format(time.UnixDate)) // Mon Jan _2 15:04:05 MST 2006
fmt.Println(now.Format(time.RubyDate)) // Mon Jan 02 15:04:05 -0700 2006
fmt.Println(now.Format(time.RFC822))   // 02 Jan 06 15:04 MST
fmt.Println(now.Format(time.RFC850))   // Monday, 02-Jan-06 15:04:05 MST
fmt.Println(now.Format(time.Kitchen))  // 3:04PM
fmt.Println(now.Format(time.Stamp))    // Jan _2 15:04:05

Go playground

Carson
  • 6,105
  • 2
  • 37
  • 45