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

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

Go 复制代码
// 格式化时间戳到字符串
// ts 时间戳 支持秒 10位, 毫秒 13位
// layout 时间格式 如果为空,则默认使用 time.RFC3339 作为格式 "2006-01-02T15:04:05Z07:00"
// 格式后的时间字符串
// @author tekintian <[email protected]>
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"

相关推荐
Fanxt_Ja1 小时前
【JVM】三色标记法原理
java·开发语言·jvm·算法
蓝婷儿1 小时前
6个月Python学习计划 Day 15 - 函数式编程、高阶函数、生成器/迭代器
开发语言·python·学习
love530love2 小时前
【笔记】在 MSYS2(MINGW64)中正确安装 Rust
运维·开发语言·人工智能·windows·笔记·python·rust
Mr Aokey2 小时前
Spring MVC参数绑定终极手册:单&多参/对象/集合/JSON/文件上传精讲
java·后端·spring
slandarer2 小时前
MATLAB | 绘图复刻(十九)| 轻松拿捏 Nature Communications 绘图
开发语言·matlab
狐凄2 小时前
Python实例题:Python计算二元二次方程组
开发语言·python
roman_日积跬步-终至千里3 小时前
【Go语言基础【3】】变量、常量、值类型与引用类型
开发语言·算法·golang
地藏Kelvin3 小时前
Spring Ai 从Demo到搭建套壳项目(二)实现deepseek+MCP client让高德生成昆明游玩4天攻略
人工智能·spring boot·后端
roman_日积跬步-终至千里3 小时前
【Go语言基础】基本语法
开发语言·golang·xcode
Felven3 小时前
C. Basketball Exercise
c语言·开发语言