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"

相关推荐
mldong8 小时前
工作流引擎的灵魂:状态机与 submitType
后端
BUG研究员_10 小时前
Runnable与LCEL
开发语言·人工智能·python
朦胧之10 小时前
Go 基础
后端·go
lun11 小时前
Agent 工具调用成长史:理清楚 Function Calling、MCP、CLI 的关系
后端
Python私教11 小时前
Codex 自动写 Commit 够安全吗?一套证据化 Git 提交流程
人工智能·git·后端
Python私教11 小时前
AI Agent 上生产要不要开写权限?我把执行链拆成 4 道闸门
人工智能·后端·python
lun11 小时前
Claude Code 多 Agent 实现:subAgent & Agent Teams
后端
牛艺翔12 小时前
C++基础
开发语言·c++
键盘会跳舞12 小时前
C++ :容器适配器stack源码级拆解
开发语言·c++··stack·先进后出
美味蛋炒饭.12 小时前
Git 版本控制(下)
开发语言·git·学习·总结·后端开发