Golang - 时间处理总结

Golang - 时间处理总结

  • 1 获取时间对象
    • 1.1 获取当前对象对象
    • 1.2 根据指定时间返回 time.Time 类型
    • 1.2 获取当前年月日时分秒、星期几、一年中的第几天等操作
    • 1.3 日期字符串解析成 time.Time 类型
        • 解析的时候需要特别注意时区的问题:
  • 2 时间对象转时间字符串
  • 3 时区
  • 4 时间运算
  • 5 时间比较
  • 6 时间戳
  • 7 常见例子
    • 7.1 time转日期字符串
    • 7.2 time转时间戳
    • 7.3 时间戳转time
    • 7.4 时间戳转日期字符串
    • 7.5 日期字符串转time
    • 7.6 日期字符串转时间戳

1 获取时间对象

1.1 获取当前对象对象

//1. 获取时间对象
now := time.Now()
fmt.Println(now) //2023-01-01 20:17:23.660881 +0800 CST m=+0.000095522

1.2 根据指定时间返回 time.Time 类型

now := time.Now()
layout := "2006-01-02 15:04:05"

//根据指定时间返回 time.Time 类型
//分别指定年,月,日,时,分,秒,纳秒,时区
t := time.Date(2011, time.Month(3), 12, 15, 30, 20, 0, now.Location())
fmt.Println(t.Format(layout))

1.2 获取当前年月日时分秒、星期几、一年中的第几天等操作

now := time.Now() //返回当前年月日时分秒、星期几、一年中的第几天等操作

// 返回日期
year, month, day := now.Date()
fmt.Printf("year:%d, month:%d, day:%d\n", year, month, day) //year:2023, month:1, day:1
// 年
fmt.Println(now.Year()) //2023
// 月
fmt.Println(now.Month()) //January
// 日
fmt.Println(now.Day()) //1

// 时分秒
hour, minute, second := now.Clock()
fmt.Printf("hour:%d, minute:%d, second:%d\n", hour, minute, second) //hour:21, minute:2, second:25
// 时
fmt.Println(now.Hour()) //21
// 分
fmt.Println(now.Minute()) //2
// 秒
fmt.Println(now.Second()) //25

// 返回星期
fmt.Println(now.Weekday()) //Sunday
//返回一年中对应的第几天
fmt.Println(now.YearDay()) //1
//返回时区
fmt.Println(now.Location()) //Local

// 返回一年中第几天
fmt.Println(now.YearDay()) //1

1.3 日期字符串解析成 time.Time 类型

//2. 时间字符串转时间对象
ts := "2022-07-01 00:00:00"
layout := "2006-01-02 15:04:05" //格式化模版
t1, err := time.Parse(layout, ts)
if err != nil {
	panic(err)
}
fmt.Println(t1) //2022-07-01 00:00:00 +0000 UTC

t, _ := time.ParseInLocation("2006-01-02 15:04:05", time.Now().Format("2006-01-02 15:04:05"), time.Local)
fmt.Println(t)  
// 输出 2021-01-10 17:28:50 +0800 CST
// time.Local 指定本地时间
解析的时候需要特别注意时区的问题:
fmt.Println(time.Now())            //2023-01-01 21:12:49.314002 +0800 CST m=+0.000078476
fmt.Println(time.Now().Location()) //Local
t, _ := time.Parse("2006-01-02 15:04:05", "2021-01-10 15:01:02")
fmt.Println(t) //2021-01-10 15:01:02 +0000 UTC
t2, _ := time.ParseInLocation("2006-01-02 15:04:05", "2021-01-10 15:01:02", time.Local)
fmt.Println(t2) //2021-01-10 15:01:02 +0800 CST

可以看到,time.Now() 使用的 CST(中国标准时间),而 time.Parse() 默认的是 UTC(零时区),它们相差 8 小时。所以解析时常用 time.ParseInLocation(),可以指定时区。

重点!!!

画了张图,帮助大家理清时间戳、time.Time 和 日期格式 之间的转化关系:

Golang - 时间处理总结_第1张图片

2 时间对象转时间字符串

Go 语言提供了时间类型格式化函数Format(),需要注意的是 Go 语言格式化时间模板不是常见的 Y-m-d H:i:s,而是 2006-01-02 15:04:05,也很好记忆(2006 1 2 3 4 5)。

//1. 获取时间对象
now := time.Now()
fmt.Println(now) //2023-01-01 20:17:23.660881 +0800 CST m=+0.000095522
//2. 时间格式化输出
layout := "2006-01-02 15:04:05" //格式化模版
fmt.Println(now.Format(layout)) //2023-01-01 20:21:39

fmt.Println(now.Format("2006-01-02"))
fmt.Println(now.Format("15:03:04"))
fmt.Println(now.Format("2006/01/02 15:04"))
fmt.Println(now.Format("15:04 2006/01/02"))

3 时区

//1. 获取时间对象
now := time.Now()
layout := "2006-01-02 15:04:05" //格式化模版
ts := "2022-07-01 00:00:00"

//4. 时区
loc1, err := time.LoadLocation("Asia/Shanghai")
if err != nil {
	panic(err)
}
t2, err := time.ParseInLocation(layout, ts, loc1)
if err != nil {
	panic(err) 
}
fmt.Println(t2) //2022-07-01 00:00:00 +0800 CST

loc2, err := time.LoadLocation("America/New_York")
if err != nil {
	panic(err)
}
fmt.Println(now.In(loc2)) //2023-01-01 07:27:14.780709 -0500 EST

4 时间运算

//获取时间对象
now := time.Now()
fmt.Println(now) //2023-01-01 20:52:18.838167 +0800 CST m=+0.000093743

//5. 时间运算
fmt.Println(now.Add(1 * time.Hour)) //当前时间+1小时     2023-01-01 21:52:18.838167 +0800 CST m=+3600.000093743
fmt.Println(now.AddDate(0, 1, 1))   //当前时间+1个月零1天 2023-02-02 20:52:18.838167 +0800 CST

// 1小时1分1s之后
t1, _ := time.ParseDuration("1h1m1s")
fmt.Println(t1)
m1 := now.Add(t1)
fmt.Println(m1)

// 1小时1分1s之前
t2, _ := time.ParseDuration("-1h1m1s")
m2 := now.Add(t2)
fmt.Println(m2)

// 3小时之前
t3, _ := time.ParseDuration("-1h")
m3 := now.Add(t3 * 3)
fmt.Println(m3)

// 10 分钟之后
t4, _ := time.ParseDuration("10m")
m4 := now.Add(t4)
fmt.Println(m4)

// Sub 计算两个时间差
sub1 := now.Sub(m3)
fmt.Println(sub1.Hours())   // 相差小时数
fmt.Println(sub1.Minutes()) // 相差分钟数

额外再介绍两个函数 time.Since()、time.Until():

// 返回当前时间与 t 的时间差,返回值是 Duration
time.Since(t Time) Duration

// 返回 t 与当前时间的时间差,返回值是 Duration
time.Until(t Time) Duration

now := time.Now()
fmt.Println(now)

t1, _ := time.ParseDuration("-1h")
m1 := now.Add(t1)
fmt.Println(m1)
fmt.Println(time.Since(m1))
fmt.Println(time.Until(m1))

输出:

2021-01-10 20:41:48.668232 +0800 CST m=+0.000095594
2021-01-10 19:41:48.668232 +0800 CST m=-3599.999904406
1h0m0.000199007s
-1h0m0.000203035s

5 时间比较

now := time.Now() 
ts := "2022-07-01 00:00:00"
layout := "2006-01-02 15:04:05" //格式化模版
t1, err := time.Parse(layout, ts)
if err != nil {
	panic(err)
}

fmt.Println(now) //2023-01-01 20:17:23.660881 +0800 CST m=+0.000095522
fmt.Println(t1) //2022-07-01 00:00:00 +0000 UTC

//6. 时间的比较
fmt.Println(now.Equal(t1))  // =
fmt.Println(now.After(t1))  // >
fmt.Println(now.Before(t1)) // <

输出:

false
true
false

6 时间戳

now := time.Now()  //2023-01-01 20:52:18.838167 +0800 CST m=+0.000093743

//7. 时间戳
fmt.Println(now.Unix())      //时间戳 秒
fmt.Println(now.UnixMilli()) //时间戳 毫秒
fmt.Println(now.UnixMicro()) //时间戳 微妙
fmt.Println(now.UnixNano())  //时间戳 纳秒

输出:

1672577538
1672577538838
1672577538838167
1672577538838167000

7 常见例子

下面列举一些常见的例子和函数封装。

7.1 time转日期字符串

const (
	YearMonthDay     = "2006-01-02"
	HourMinuteSecond = "15:04:05"
	DefaultLayout    = YearMonthDay + " " + HourMinuteSecond
)

// time转为默认格式的日期字符串
func TimeToDefaultStr(t time.Time) string {
	return TimeToStr(t, DefaultLayout)
}

// time转换为指定格式的日期字符串
func TimeToStr(t time.Time, layout string) string {
	return t.Format(layout)
}

7.2 time转时间戳

// time转换为秒级时间戳
func TimeToUnixSecond(t time.Time) int64 {
	return t.Unix()
}

// time转换为毫秒级别时间戳
func TimeToUnixMilli(t time.Time) int64 {
	return TimeToUnixNano(t) / 1000
}

// time转换为纳秒级别时间戳
func TimeToUnixNano(t time.Time) int64 {
	return t.UnixNano()
}

7.3 时间戳转time

// 秒级时间戳转time
func UnixSecondToTime(second int64) time.Time {
	return time.Unix(second, 0)
}

// 毫秒级时间戳转time
func UnixMilliToTime(milli int64) time.Time {
	return time.Unix(milli/1000, (milli%1000)*(1000*1000))
}

// 纳秒级时间戳转time
func UnixNanoToTime(nano int64) time.Time {
	return time.Unix(nano/(1000*1000*1000), nano%(1000*1000*1000))
}

7.4 时间戳转日期字符串

const (
	YearMonthDay     = "2006-01-02"
	HourMinuteSecond = "15:04:05"
	DefaultLayout    = YearMonthDay + " " + HourMinuteSecond
)

// 秒级时间戳转默认格式日期字符串
func UnixSecondToDefaultTimeStr(second int64) string {
	return UnixSecondToTimeStr(second, DefaultLayout)
}

// 毫秒级时间戳转默认格式日期字符串
func UnixMilliToDefaultTimeStr(milli int64) string {
	return UnixMilliToTimeStr(milli, DefaultLayout)
}

// 纳秒级时间戳转默认格式日期字符串
func UnixNanoToDefaultTimeStr(nano int64) string {
	return UnixNanoToTimeStr(nano, DefaultLayout)
}

// 秒级时间戳转指定格式日期字符串
func UnixSecondToTimeStr(second int64, layout string) string {
	return TimeToStr(UnixSecondToTime(second), layout)
}

// 毫秒级时间戳转指定格式日期字符串
func UnixMilliToTimeStr(second int64, layout string) string {
	return TimeToStr(UnixMilliToTime(second), layout)
}

// 纳秒级时间戳转指定格式日期字符串
func UnixNanoToTimeStr(nano int64, layout string) string {
	return TimeToStr(UnixNanoToTime(nano), layout)
}

7.5 日期字符串转time

const (
	YearMonthDay     = "2006-01-02"
	HourMinuteSecond = "15:04:05"
	DefaultLayout    = YearMonthDay + " " + HourMinuteSecond
)

// 默认格式日期字符串转time
func TimeStrToTimeDefault(str string) time.Time {
	parseTime, _ := time.ParseInLocation(DefaultLayout, str, time.Local)
	return parseTime
}

// 指定格式日期字符串转time
func TimeStrToTime(str, layout string) time.Time {
	parseTime, _ := time.ParseInLocation(layout, str, time.Local)
	return parseTime
}

7.6 日期字符串转时间戳

const (
	YearMonthDay     = "2006-01-02"
	HourMinuteSecond = "15:04:05"
	DefaultLayout    = YearMonthDay + " " + HourMinuteSecond
)


// 默认格式日期字符串转秒时间戳
func TimeStrToUnixSecondDefault(str string) int64 {
	return TimeStrToTimeDefault(str).Unix()
}

// 默认格式日期字符串转毫秒时间戳
func TimeStrToUnixMilliDefault(str string) int64 {
	return TimeStrToUnixNanoDefault(str) / 1000
}

// 默认格式日期字符串转纳秒时间戳
func TimeStrToUnixNanoDefault(str string) int64 {
	return TimeStrToTimeDefault(str).UnixNano()
}

// 指定格式日期字符串转秒时间戳
func TimeStrToUnixSecond(str, layout string) int64 {
	return TimeStrToTime(str, layout).Unix()
}

// 指定格式日期字符串转毫秒时间戳
func TimeStrToUnixMilli(str, layout string) int64 {
	return TimeStrToUnixNano(str, layout) / (1000 * 1000)
}

// 指定格式日期字符串转纳秒时间戳
func TimeStrToUnixNano(str, layout string) int64 {
	return TimeStrToTime(str, layout).UnixNano()
}

// 默认格式日期字符串转time
func TimeStrToTimeDefault(str string) time.Time {
	parseTime, _ := time.ParseInLocation(DefaultLayout, str, time.Local)
	return parseTime
}

// 指定格式日期字符串转time
func TimeStrToTime(str, layout string) time.Time {
	parseTime, _ := time.ParseInLocation(layout, str, time.Local)
	return parseTime
}

你可能感兴趣的:(Golang,golang,开发语言,后端)