go格式化时间

160 阅读1分钟

前言

在使用go开发中,有时候需要格式化时间,go语言的格式化时间有点特殊,使用2006-01-02 15:04:05

go格式化时间

格式化时间

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    a := now.Format("2006-01-02 15:04:05")
    fmt.Println(a)
}

输出结果为

image.png

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    a := now.Format("2006-01-02")
    fmt.Println(a)
}

输出结果为

image.png

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now() 
    a := now.Format("15:04:05")
    fmt.Println(a)
}

输出结果为

image.png

可以使用中文

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    a := now.Format("2006年01月02日 15时04分05秒")
    fmt.Println(a)
}

输出结果为

image.png

12小时制和AM/PM

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    a := now.Format("2006-01-02 03:04:05 PM")
    fmt.Println(a)
}

输出结果为

image.png

毫秒、微秒、纳秒

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    a := now.Format("2006-01-02 03:04:05.000")
    fmt.Println(a)
}

输出结果为

image.png

总结

time.Format() 方法的参数不是一个“模式字符串”,而是一个具体的日期时间示例。你必须使用 20060102150405 这些固定数字来代表对应的年、月、日、时、分、秒。