Go_21: Golang 中 time 包的使用二

常量声明:

const TimeLayout = "2006-01-02 15:04:05"

  这是个奇葩,必须是这个时间点,据说是 go 诞生之日, 记忆方法:6-1-2-3-4-5 

1. 获取当前时间戳

func GetCurrentSystemTimestamp() int64 {
    return time.Now().Unix()
}

2. 获取当前 string 时间

func GetCurrentSystemTimeStr() string {
    return time.Now().Format(TimeLayout)
}

3. 时间戳 转 string时间格式

func Timestamp2StandardTimeStr(timestamp int64) string {
    return time.Unix(timestamp, 0).Format(TimeLayout)
}

4. string时间 转 时间戳

  这个稍微有点复杂,golang 语言中在进行此项时间转换是,如果直接使用的是 parse 进行格式化,默认会使用 UTC 格式。那么到底什么是 UTC 时间格式呢?

  整个地球分为二十四时区,每个时区都有自己的本地时间。在国际无线电通信场合,为了统一起见,使用一个统一的时间,称为通用协调时(UTC, Universal Time Coordinated)。UTC 与 格林尼治平均时(GMT, Greenwich Mean Time)一样,都与英国伦敦的本地时相同。北京时区是东八区,领先 UTC 八个小时,故如果传入字符串为:2017-11-13 11:14:21,结果会返回 UTC 转换后的时间戳为:1510571661(2017-11-13 19:14:21)。

  要想解决这个问题,需要使用 time 为我们提供的另外一个解析函数:parseInLocaltion

复制代码
func TimeStr2Timestamp(timeStr string) int64 {
    // 得到本地时区
    loc, _ := time.LoadLocation("Local")
    // 读取文件中的时间字符串末尾会带有换行符,需要将其去掉否则解析异常
    tm, error := time.ParseInLocation(TimeLayout, strings.Trim(timeStr, "\n"), loc)
    if error != nil {
        log.Fatal(error)
        return 0
    }
    return tm.Unix()
}
复制代码

 

posted @   星火燎原智勇  阅读(556)  评论(0)    收藏  举报
编辑推荐:
· 如何统计不同电话号码的个数?—位图法
· C#高性能开发之类型系统:从 C# 7.0 到 C# 14 的类型系统演进全景
· 从零实现富文本编辑器#3-基于Delta的线性数据结构模型
· 记一次 .NET某旅行社酒店管理系统 卡死分析
· 长文讲解 MCP 和案例实战
阅读排行:
· 用c#从头写一个AI agent,实现企业内部自然语言数据统计分析
· 三维装箱问题(3D Bin Packing Problem, 3D-BPP)
· MCP协议Streamable HTTP
· Windows上,10分钟构建一个本地知识库
· 容器化 MCP Server!
点击右上角即可分享
微信分享提示