blob: 44a41569eef4c045d01d585b9842203a2a83d85d (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
---
title: 'Golang: Format Date and Time'
description: "Most programming languages use the same layout (dd-mm-yyyy) to format date and time, but Go decided to go a different route. Below is a little cheat sheet of how to format date and time in Go."
date: 2021-08-13T00:00:00+01:00
tags: ['go', 'golang']
draft: false
---
Most programming languages use the same layout (dd-mm-yyyy) to format date and time, but Go decided to go a different route. Below is a little cheat sheet of how to format date and time in Go.
<!--more-->
## Examples
### Parsing exisiting date
```go
var (
timeToParse = "2021-09-13T07:43:52.823"
layout = "2006-01-02T03:04:05.999"
)
toTime, _ := time.Parse(layout, timeToParse)
fmt.Printf("(%T): %s\n", toTime, toTime)
// output: (time.Time): 2021-09-13 07:43:52.823 +0000 UTC
```
### Formatting date
```go
now := time.Now()
fmt.Println("Default:", now)
fmt.Println("Formatted:", now.Format("02-01-2006 15:04:05 -0700 MST"))
// output: Default: 2021-08-13 09:01:29.233757 +0200 CEST m=+0.000065018
// output: Formatted: 13-08-2021 09:01:29 +0200 CEST
```
## Options
| Type | Options |
| :------- | :---------------------------- |
| Year | 06 2006 |
| Month | 01 1 Jan January |
| Day | 02 2 \_2 |
| Weekday | Mon Monday |
| Hours | 03 3 15 |
| Minutes | 04 4 |
| Seconds | 05 5 |
| ms μs ns | .000 .000000 .000000000 |
| ms μs ns | .999 .999999 .999999999 |
| am / pm | PM pm |
| Timezone | MST |
| Offset | -0700 -07 -07:00 Z0700 Z07:00 |
## Predefined layouts
| Name | Layout |
| :---------- | :----------------------------------------------------------- |
| ANSIC | Mon Jan \_2 15:04:05 2006 |
| UnixDate | Mon Jan \_2 15:04:05 MST 2006 |
| RubyDate | Mon Jan 02 15:04:05 -0700 2006 |
| RFC822 | 02 Jan 06 15:04 MST |
| RFC822Z | 02 Jan 06 15:04 -0700 // RFC822 with numeric zone |
| RFC850 | Monday, 02-Jan-06 15:04:05 MST |
| RFC1123 | Mon, 02 Jan 2006 15:04:05 MST |
| RFC1123Z | Mon, 02 Jan 2006 15:04:05 -0700 // RFC1123 with numeric zone |
| RFC3339 | 2006-01-02T15:04:05Z07:00 |
| RFC3339Nano | 2006-01-02T15:04:05.999999999Z07:00 |
| Kitchen | 3:04PM |
| Stamp | Jan \_2 15:04:05 |
| StampMilli | Jan \_2 15:04:05.000 |
| StampMicro | Jan \_2 15:04:05.000000 |
| StampNano | Jan \_2 15:04:05.000000000 |
|