til/Development/Go/time.md

74 lines
1.3 KiB
Markdown
Raw Normal View History

2020-05-11 16:28:10 +00:00
# [time](https://golang.org/pkg/time/)
To parse string to time in golang, must define layout first.
Read default layouts in [Constants](https://golang.org/pkg/time/#pkg-constants).
The reference time:
```txt
Mon Jan 2 15:04:05 MST 2006
```
To define your layout, rewrite reference time in your layout.
2020-08-04 10:59:39 +00:00
Example `time.Parse` from `string` to `time.Time`:
2020-05-11 16:28:10 +00:00
```go
layout := "2006-01-02 15:04:05"
t, err := time.Parse(layout, "2020-06-09 23:04:02")
if err != nil {
log.Fatal(err)
}
fmt.Println(t)
```
2020-08-04 10:59:39 +00:00
Example `time.ParseInLocation` from `string` to `time.Time` with location:
2020-05-11 16:28:10 +00:00
```go
layout := "2006-01-02 15:04:05"
loc, err := time.LoadLocation("Asia/Ho_Chi_Minh")
if err != nil {
log.Fatal(err)
}
t, err := time.ParseInLocation(layout, "2020-06-09 23:04:02", loc)
if err != nil {
log.Fatal(err)
}
fmt.Println(t)
```
2020-06-30 09:12:17 +00:00
2020-08-04 10:59:39 +00:00
Example `Format` from `time.Time` to `string`:
2020-06-30 09:12:17 +00:00
```go
now := time.Now()
layout := "2006-01-02"
fmt.Println(now.Format(layout))
```
2020-08-04 10:59:39 +00:00
Example `Format` from `time.Time` to `string` with location:
2020-06-30 09:12:17 +00:00
```go
loc, err := time.LoadLocation("Asia/Ho_Chi_Minh")
if err != nil {
return "", err
}
now := time.Now().In(loc)
layout := "2006-01-02"
fmt.Println(now.Format(layout))
```
2020-08-04 10:59:39 +00:00
Example `time.Unix` from timestamp ms to `time.Time`:
```go
time.Unix(0, timestamp * int64(time.Millisecond))
```