golang 转换时间戳到字符串函数 支持秒和毫秒时间戳 转换到自定字符串

golang 转换时间戳到字符串函数 支持秒和毫秒时间戳 转换到自定字符串, 自动判断是秒还是毫秒时间戳, 废话不多说,直接上代码:

Go 复制代码
// 格式化时间戳到字符串
// ts 时间戳 支持秒 10位, 毫秒 13位
// layout 时间格式 如果为空,则默认使用 time.RFC3339 作为格式 "2006-01-02T15:04:05Z07:00"
// 格式后的时间字符串
// @author tekintian <tekintian@gmail.com>
func TsToStr(ts int64, layout string) string {
	var t time.Time
	if ts < 9999999999 { // 当前的时间戳是秒 秒的时间戳最长10位, 毫秒的时间戳长度为13位
		t = time.Unix(ts, 0)
	} else {
		t = time.UnixMilli(ts)
	}
	// 格式化时间字符串
	if layout == "" {
		layout = time.RFC3339
	}
	return t.Format(layout)
}

ps: 如果希望返回的时间字符串为默认的格式 time.RFC3339 即 "2006-01-02T15:04:05Z07:00" , 则第二个参数直接传递空字符串即可,即: TsToStr(1722657237,"")

更多字符串相关函数库安装: go get github.com/tekintian/strutils

使用 strutils.TsToStr(1722683285997,"") // 输出 "2024-08-03T19:08:05+08:00"

相关推荐
t***5446 小时前
如何配置Orwell Dev-C++使用Clang
开发语言·c++
CoderCodingNo6 小时前
【信奥业余科普】C++ 的奇妙之旅 | 13:为什么 0.1+0.2≠0.3?——解密“爆int”溢出与浮点数精度的底层原理
开发语言·c++
杨凯凡6 小时前
【021】反射与注解:Spring 里背后的影子
java·后端·spring
Ares-Wang7 小时前
Flask》》 Flask-Bcrypt 哈希加密
后端·python·flask
小码哥_常7 小时前
Spring Boot项目大变身:为何要拆成这六大模块?
后端
kongba0077 小时前
项目打包 Python Flask 项目发布与打包专家 提示词V1.0
开发语言·python·flask
froginwe118 小时前
C 语言测验
开发语言
今夕资源网8 小时前
powershell工具包 安装升级脚本并设置UTF-8 环境快捷方式创建 将powershell的编码默认改为UTF-8
开发语言·utf-8·powershell·utf-8编码·powershell7·powershell5·设置utf-8编码
机器视觉知识推荐、就业指导8 小时前
Qt:真正的门槛不是入门,而是维护
开发语言·qt
hhb_6189 小时前
Dylan 语言核心特性与工程实践深度解析
开发语言·c#