【Go】时间

mysql中的datetime转时间戳

// 获取mysql中的datetime类型转时间戳
t := "2023-02-21T14:51:00+08:00"
ts, _ := time.ParseInLocation(time.RFC3339, t, time.Local)
loc, _ := time.LoadLocation("Local")
timeLayout := "2006-01-02 15:04:05"
theTime, _ := time.ParseInLocation(timeLayout, ts.Format("2006-01-02 15:04:05"), loc) //使用模板在对应时区转化为time.time类型
sr := theTime.Unix()
fmt.Println(sr)

String转Time

常规格式

t, _ := time.ParseInLocation("2006-01-02 15:04:05", "2022-12-15 14:35:31", time.Local)
fmt.Println(t)  // 2022-12-15 14:35:31 +0800 CST
ts, _ := time.ParseInLocation(time.RFC3339, "2022-12-15T14:35:31+08:00", time.Local)
fmt.Println(ts)  // 2022-12-15 14:35:31 +0800 CST

image

time转string

t := "2023-02-21T14:51:00+08:00"
ts, _ := time.ParseInLocation(time.RFC3339, t, time.Local)
fmt.Println(ts.Format("2006-01-02 15:04:05"))  // 2023-02-21 14:51:00

获取当前时间字符串

date := time.Now().Format("2006-01-02 15:04:05")
date := time.Now().Format("2006-01-02 00:00:00")
fmt.Printf("当前时间:%v", date)

获取时间戳

获取当前时间的时间戳

now:= time.Now()
fmt.Println(now.Unix()) // 1565084298 秒
fmt.Println(now.UnixNano()) // 1565084298178502600 纳秒
fmt.Println(now.UnixNano() / 1e6) // 1565084298178 毫秒

获取指定时间的时间戳

date := time.Now().Format("2006-01-02 00:00:00")
toBeCharge := date                                              //待转化为时间戳的字符串 注意 这里的小时和分钟还要秒必须写 因为是跟着模板走的 修改模板的话也可以不写
timeLayout := "2006-01-02 15:04:05"                             //转化所需模板
loc, _ := time.LoadLocation("Local")                            //重要:获取时区
theTime, _ := time.ParseInLocation(timeLayout, toBeCharge, loc) //使用模板在对应时区转化为time.time类型
sr := theTime.Unix()                                            //转化为时间戳 类型是int64
fmt.Println(theTime)                                            //打印输出theTime 2015-01-01 15:15:00 +0800 CST
fmt.Println(sr)                                                 //打印输出时间戳 1420041600

时间戳转字符串

package main

import (
    "fmt"
    "time"
)

func main() {
    // 获取当前时间戳
    timestamp := time.Now().Unix()

    // 将时间戳转换为时间格式
    tm := time.Unix(timestamp, 0)

    // 将时间格式转换为字符串格式
    str := tm.Format("2006-01-02 15:04:05")

    // 输出字符串格式的时间
    fmt.Println(str)
}
posted @ 2022-12-15 16:09  小魁jking  阅读(51)  评论(0)    收藏  举报