golang时间日期处理

时间处理
  • import “time”
时间戳
time.Now().Unix()
时间格式化
time.Now().Format("2006-01-02 15:04:05")

时间点必须为2006-01-02 15:04:05, go语言诞生之日
时间戳转字符串格式化时间
str_time := time.Unix(1389058332, 0).Format("2006-01-02 15:04:05")
fmt.Println(str_time)
字符串格式化时间转时间戳
the_time, err := time.Parse("2006-01-02 15:04:05", "2014-01-08 09:04:41")
if err == nil {
    unix_time := the_time.Unix()
	fmt.Println(unix_time)		
}
检查两个时间对象是否在同一日期
func DateEqual(t1 time.Time, t2 time.Time) bool {
	y1, m1, d1 := t1.Date()
	y2, m2, d2 := t2.Date()
	return y1 == y2 && m1 == m2 && d1 == d2
}

func DateEqual(date1, date2 time.Time) bool {
    return date1.Format("20060102") == date2.Format("20060102")
}

时区问题
  • UTC表示世界协调时间(Coordinated Universal Time)

世界协调时间(UTC)与世界协调时间(UTC)没有时差。

  • CST表示中国标准时间(China Standard Time)

中国标准时间(CST)比世界协调时间(UTC)快08:00小时。该时区为标准时区时间,主要用于 亚洲

  • 世界协调时间(UTC)=UTC+ 00:00
  • 中国标准时间(CST)=UTC+ 08:00
time.Now() 默认CST时区时间, 当地时间
time.Now().Format("2006-01-02 15:04:05")
time.Now()返回的是当地时区时间

源码
// Now returns the current local time.
func Now() Time {
	sec, nsec, mono := now()
	mono -= startNano
	sec += unixToInternal - minWall
	if uint64(sec)>>33 != 0 {
		return Time{uint64(nsec), sec + minWall, Local}
	}
	return Time{hasMonotonic | uint64(sec)<<nsecShift | uint64(nsec), mono, Local}
}
更改时区,需要调用一个In()函数改变时区
  • time.FixedZone
var cstZone = time.FixedZone("CST", 8*3600)         // 东八
fmt.Println(time.Now().In(cstZone).Format("2006-01-02 15:04:05"))
  • time.LoadLocation
var cstSh, _ = time.LoadLocation("Asia/Shanghai") //  上海
fmt.Println(time.Now().In(cstSh).Format("2006-01-02 15:04:05"))
time.Parse()默认是UTC时区时间
  • time.Parse() returns a time.Time having UTC zone by default (if zone info is not part of the input and layout).

  • time. parse() 返回一个时间。默认的UTC时区时间(如果时区信息不是输入和layout的一部分)。

  • 时间字符串转为本地时间

t, _ := time.ParseInLocation("2006-01-02 15:04:05", "2021-09-17 11:00:00", time.Local)
时间戳,两个时区不同的time类型,比较时间戳会出错
  • time.Unix() returns the local Time, 返回UTC+ 08:00
  • 当UTC时区的时间直接调用Unix()函数返回的时间就会出现加了8个小时
  • time.Unix()函数返回公元1970年1月,1日,0时,0分,0秒以来的秒数
t1, _ = time.Parse("2006-01-02 15:04:05", "2021-09-17 11:00:00")
now = time.Now()

t1.Unix()的值为 1631876400,2021-09-17 19:00:00,所以直接判断t1.Unix()和now.Unix()是错误的
所以t1要转换为本地时区,再做比较
t1Loc, _ := time.ParseInLocation("2006-01-02 15:04:05", t1.Format("2006-01-02 15:04:05"), time.Local)

time.Format 的时区信息来源于 Time 结构体中的 loc
  • 用了time.Parse()后, loc默认就是time.Local,所以UTC时间Format后的时间也是对的
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值