go修改服务器时间,go的时间转换和比较

时间转换timeLayout := "2006-01-02 15:04:05"

1.获取服务器时间fmt.Println(time.Now().Format(timeLayout))

2.获取UTC时间fmt.Println(time.Now().UTC().Format(timeLayout))

3.服务器时间转换为UTC时间timeStr := "2021-05-18 12:00:00" // 认为服务器时间

location, _ := time.LoadLocation("Local") // timeStr是北京时间,注意使用Local

localTime, _ := time.ParseInLocation(timeLayout, timeStr, location)

fmt.Println(localTime.UTC().Format(timeLayout)) // 转为UTC时间

说明:注意timeStr值,此时我们把它当做服务器时间,所以time.LoadLocation("Local") 使用Local

4.UTC时间转换为服务器时间timeStr := "2021-05-18 12:00:00" // 认为是UTC器时间

location, _ := time.LoadLocation("UTC") // timeStr是北京时间,注意使用UTC

localTime, _ := time.ParseInLocation(timeLayout, timeStr, location)

fmt.Println(localTime.Local().Format(timeLayout)) // 转为Local服务器时间

说明:注意timeStr值,此时我们把它当做UTC时间,所以time.LoadLocation("UTC") 使用Local

时间比较timeLayout := "2006-01-02 15:04:05"timeStr := "2021-05-17 11:00:00" // 认为服务器时间

location, _ := time.LoadLocation("Local") // timeStr是北京时间,注意使用Local

localTime, _ := time.ParseInLocation(timeLayout, timeStr, location)

fmt.Println(localTime.UTC().Format(timeLayout)) // 转为UTC时间

compareTimeStr := "2021-05-17 02:00:00" // 认为UTC时间

location, _ = time.LoadLocation("UTC") // timeStr是北京时间,注意使用UTC

compareTime, _ := time.ParseInLocation(timeLayout, compareTimeStr, location)

fmt.Println(compareTime.Local().Format(timeLayout)) // 转为服务器时间

fmt.Println("------------------------------------")

fmt.Println(compareTime.Before(localTime)) // Before 会统一时间基准点

fmt.Println(compareTime.After(localTime)) // After 会统一时间基准点

说明: Before After会统一时间基准点,可以不用担心因为时区的问题导致时间比较错误,但要注意转为golang time.Time时候的时区问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值