在 Go 中,将时间戳转换为时间值的方法:导入 time 包。使用 time.Unix() 或 time.UnixMilli() 转换时间戳为 time.Time 值。根据需要使用 time.Format() 格式化时间值为字符串。

如何将 Golang 时间戳转换为时间
在 Golang 中,将时间戳转换为时间值非常简单。时间戳是表示自纪元时间(通常为 1970 年 1 月 1 日 00:00:00 UTC)以来经过的秒数或纳秒数。
步骤 1:导入 time 包
首先,你需要导入 Go 的 time 包,它提供了与时间相关的功能。
立即学习“go语言免费学习笔记(深入)”;
<code class="go">import "time"</code>
步骤 2:创建 time.Time 值
要将时间戳转换为 time.Time 值,可以使用 time.Unix() 或 time.UnixMilli() 函数。
time.Unix(sec, nsec):将秒(sec)和纳秒(nsec)转换为 time.Time 值。time.UnixMilli(msec):将毫秒(msec)转换为 time.Time 值,实际上调用 time.Unix(msec/1000, (msec%1000)*1000000)。例如,要将 Unix 时间戳 1640995200 转换为 time.Time 值,可以使用以下代码:
<code class="go">timestamp := int64(1640995200) t := time.Unix(timestamp, 0)</code>
步骤 3:格式化时间
转换为 time.Time 值后,你可以使用 time.Format() 函数将它格式化为字符串。例如,要将时间格式化为 "2022-01-01 12:00:00",可以使用以下代码:
<code class="go">fmt.Println(t.Format("2006-01-02 15:04:05"))</code>输出:
<code>2022-01-01 12:00:00</code>
以上就是golang时间戳怎么转时间的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号