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"

相关推荐
tang&25 分钟前
【Python自动化测试】Selenium常用函数详解
开发语言·python·selenium
卜锦元1 小时前
Golang项目开发过程中好用的包整理归纳(附带不同包仓库地址)
开发语言·后端·golang
Tony Bai5 小时前
“我曾想付钱给 Google 去工作”—— Russ Cox 深度访谈:Go 的诞生、演进与未来
开发语言·后端·golang
sali-tec5 小时前
C# 基于halcon的视觉工作流-章66 四目匹配
开发语言·人工智能·数码相机·算法·计算机视觉·c#
hnlgzb6 小时前
安卓app开发,如何快速上手kotlin和compose的开发?
android·开发语言·kotlin
无敌最俊朗@7 小时前
STL-deque面试剖析(面试复习4)
开发语言
APIshop7 小时前
用 Python 把“API 接口”当数据源——从找口子到落库的全流程实战
开发语言·python
serendipity_hky7 小时前
【SpringCloud | 第2篇】OpenFeign远程调用
java·后端·spring·spring cloud·openfeign
Java Fans7 小时前
Qt Designer 和 PyQt 开发教程
开发语言·qt·pyqt
RwTo7 小时前
【源码】-Java线程池ThreadPool
java·开发语言