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"

相关推荐
chéng ௹10 小时前
前端转编码(encodeURIComponent)以及解码(decodeURIComponent)
开发语言·前端·javascript
bbq粉刷匠10 小时前
java刷题-day1
java·开发语言
温轻舟10 小时前
禁毒路上,任重道远 | HTML页面
开发语言·前端·javascript·css·html·温轻舟
p***q7810 小时前
SpringBoot实战:高效实现API限流策略
java·spring boot·后端
学历真的很重要10 小时前
Hello-Agents —— 03大语言模型基础 通俗总结
开发语言·人工智能·后端·语言模型·自然语言处理·面试·langchain
6***v41711 小时前
VScode 开发 Springboot 程序
java·spring boot·后端
t***316511 小时前
SpringBoot中自定义Starter
java·spring boot·后端
z***33511 小时前
SpringBoot获取bean的几种方式
java·spring boot·后端
wefg111 小时前
【C++】IO流
开发语言·c++
s***469811 小时前
【SpringBoot篇】详解Bean的管理(获取bean,bean的作用域,第三方bean)
java·spring boot·后端