Member-only story

Date packages in Go

Beck Moulton
4 min readMay 1, 2023

--

This article will introduce the date package in the Go language and explain its use details in detail

#1 Common functions

  1. 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…

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet