Member-only story
Date packages in Go
This article will introduce the date package in the Go language and explain its use details in detail
#1 Common functions
- time.Now (): Get the current time
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
fmt.Println(now)
}
2. Time.Parse (): Parses the time string to the Time type
package main
import (
"fmt"
"time"
)
func main() {
str := "2023-05-02 15:04:05"
t, err := time.Parse("2006-01-02 15:04:05", str)
if err != nil {
fmt.Println("parse error:", err)
return
}
fmt.Println(t)
}
Parsing the time string requires providing a formatted string, where 2006, 01, 02, 15, 04, 05 are fixed, representing year, month, day, hour, minute, second. This is because the release date of the Go language is January 2, 2006 15:04:05.
3. Time.Format (): Format Time as string
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
str := now.Format("2006-01-02 15:04:05")
fmt.Println(str)
}
The formatted string is the same as the parsed string, which is composed of fixed numbers and symbols, representing the year, month, day, etc. Here, now. Format (“2006–01–02 15:04:05”) represents a string…