Golang中的日期时间格式化详情使用指南

23 min read

Golang中日期时间格式化有两种方式:

  1. 使用time包的Format函数。
  2. 使用strconv包的FormatInt和FormatFloat函数。

以下是Golang中日期时间格式化的使用指南:

  1. 使用time包的Format函数

time包中的Format函数可以将时间类型的变量格式化成指定格式的字符串。以下是常用的格式化字符串:

日期格式:
2006-01-02 15:04:05
Year   | Month |Day | Hour | Min | Second

周几表示:
周几  Mon    (表示对应英文的缩写)
周几  Mon    (表示对应英文全称)
1~7   1~7    (表示一周的第几天,周日从1开始)

时间格式:
15:04:05 (小时:分钟:秒)

使用示例代码:

package main

import (
    "fmt"
    "time"
)

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

    // 输出:
    //2022-01-03 14:21:10
}
  1. 使用strconv包的FormatInt和FormatFloat函数

strconv包中的FormatInt和FormatFloat函数可以将整型和浮点型格式化成字符串。以下是示例代码:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    var i int64 = 123
    fmt.Println(strconv.FormatInt(i, 10))
    // 输出:123

    var f float64 = 123.456
    fmt.Println(strconv.FormatFloat(f, 'f', -1, 64))
    // 输出:123.456
}

参考链接:https://www.jianshu.com/p/19fe041f1945