|
| 1 | +# Format Date And Time With Time Constants |
| 2 | + |
| 3 | +The Go [`time` package](https://pkg.go.dev/time) has a [`Format` |
| 4 | +function](https://pkg.go.dev/time#Time.Format) for displaying the parts of a |
| 5 | +date and time in standard and custom ways. It works a bit different than you |
| 6 | +might be used to from other languages. Rather than using `strftime` identifiers |
| 7 | +like in this string `"%B %d, %Y"`, there is a canonical date that is used as a |
| 8 | +reference point. |
| 9 | + |
| 10 | +That canonical date is from Janary 2nd, 2006. That was a Monday. It was at 5 |
| 11 | +seconds after 3:04PM. The Unix format of it looks like `"Mon Jan _2 15:04:05 |
| 12 | +MST 2006"`. |
| 13 | + |
| 14 | +``` |
| 15 | +package main |
| 16 | +
|
| 17 | +import ( |
| 18 | + "fmt" |
| 19 | + "time" |
| 20 | +) |
| 21 | +
|
| 22 | +func main() { |
| 23 | + // This specific time pulled from `time.Format` docs |
| 24 | + t, _ := time.Parse(time.UnixDate, "Wed Feb 25 11:06:39 PST 2015") |
| 25 | +
|
| 26 | + // Reference date and time: |
| 27 | + // "Mon Jan _2 15:04:05 MST 2006" |
| 28 | +
|
| 29 | + strf1 := t.Format("|2006|02|01|03:04:05|Day: Mon|") |
| 30 | + fmt.Println("strf1:", strf1) |
| 31 | + // strf1: |2015|25|02|11:06:39|Day: Wed| |
| 32 | +
|
| 33 | + strf2 := t.Format(time.DateTime) |
| 34 | + strf3 := t.Format(time.RubyDate) |
| 35 | + strf4 := t.Format(time.Kitchen) |
| 36 | +
|
| 37 | + fmt.Println("DateTime:", strf2) // DateTime: 2015-02-25 11:06:39 |
| 38 | + fmt.Println("RubyDate:", strf3) // RubyDate: Wed Feb 25 11:06:39 +0000 2015 |
| 39 | + fmt.Println("Kitchen:", strf4) // Kitchen: 11:06AM |
| 40 | +} |
| 41 | +``` |
| 42 | + |
| 43 | +Though there are a [variety of useful formatting |
| 44 | +constants](https://pkg.go.dev/time#pkg-constants) already available like |
| 45 | +`DateTime`, `RubyDate`, `Kitchen`, etc., we can also define our own formatting |
| 46 | +string by using the reference values for each part of a date and time. |
| 47 | + |
| 48 | +If you want to reference the year, whether as `YYYY` or `YY`, it is always |
| 49 | +going to be a form of `2006`, so `2006` or `06` respectively. Even though the |
| 50 | +above time variable is in February, our format strings will always need to use |
| 51 | +one of `Jan`, `January`, `01` or `1`. |
0 commit comments