Go Lang日期时间与unix时间戳互转
1.Go lang中日期时间转unix时间戳,10位unix时间戳转日期时间格式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | /* * DES:日期时间格式转unix时间戳 和 unix时间戳转日期时间格式 */ package main import ( "fmt" "time" ) func main() { // 1.获取当前日期时间 date_now := GetDateNow() fmt.Println( "当前日期时间:" , date_now) // 2.当前日期时间转换为10位时间戳 unix_date := DateAndUnix(date_now) fmt.Println( "日期时间格式" , date_now, "转为unix时间戳是:" , unix_date) // 3.当前日期时间的10位unix时间戳转日期时间格式 unix_time := time.Now().Unix() // 取当前日期时间戳 logindate := UnixAndDate(unix_time) // 当前日期unix时间戳转日期时间格式 fmt.Println( "unix时间戳:" , unix_time, "转换为日期格式是:" , logindate) } /* * 获取系统当前日期时间 * 返回东八区日期时间格式 : 2021-05-26 14:51:07 */ func GetDateNow() string { /* go语言并没有全局设置时区这么一个东西,每次输出时间都需要调用一个In()函数改变时区: var location, _ = time.LoadLocation("Asia/Shanghai") //上海 DateNow := time.Now().In(location).Format("2006-01-02 15:04:05") 在windows系统上,没有安装go语言环境的情况下,time.LoadLocation会加载失败。最好的办法是用time.FixedZone */ var location = time.FixedZone( "CST" , 8*3600) // 设置时区为东八区 timeLayout := "2006-01-02 15:04:05" // go语言固定日期模版 DateNow := time.Now().In(location).Format(timeLayout) return string (DateNow) } /* * Unix时间戳转为日期时间 * prarms: 传入10位数的unix_time时间戳 * 返回东八区日期时间格式: 2021-05-26 14:51:07 */ func UnixAndDate(unix_date int64) string { var location = time.FixedZone( "CST" , 8*3600) // 设置时区为东八区 timeLayout := "2006-01-02 15:04:05" // go语言固定日期模版 tm := time.Unix(unix_date, 0).In(location).Format(timeLayout) return string (tm) } /* * 日期时间转换为时间戳 * date: 传入日期时间格式的数据 * 返回10位数的unix时间戳: 1622012890 */ func DateAndUnix(date string ) int64 { timeLayout := "2006-01-02 15:04:05" // go语言固定日期模版 times, _ := time.Parse(timeLayout, date) timeUnix := times.Unix() return timeUnix } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」