随笔:Golang 时间Time

先了解下time类型:函数

type Time struct {this

// sec gives the number of seconds elapsed sincespa

// January 1, year 1 00:00:00 UTC.orm

sec int64ci

 

// nsec specifies a non-negative nanosecond字符串

// offset within the second named by Seconds.it

// It must be in the range [0, 999999999].io

nsec int32class

 

// loc specifies the Location that should be used tosed

// determine the minute, hour, month, day, and year

// that correspond to this Time.

// Only the zero Time has a nil Location.

// In that case it is interpreted to mean UTC.

loc *Location

}

对于time.Time类型,咱们能够经过使用函数Before,After,Equal来比较两个time.Time时间:

t1 := time.Now()

t2 := t1.Add(-1 * time.Minute)

fmt.Println(t1.Before(t2))

上面t1是当前时间,t2是当前时间的前一分钟,输出结果:false

对于两个time.Time时间是否相等,也能够直接使用==来判断:

t1 := time.Now()

t2 := t1.Add(-1 * time.Minute)

fmt.Println(t1 == t2)

 

咱们能够经过IsZero来判断时间Time的零值

t1.IsZero()

 

咱们经常会将time.Time格式化为字符串形式:

t := time.Now()

str_t := t.Format("2006-01-02 15:04:05")

至于格式化的格式为何是这样的,已经被不少人吐槽了,可是,这是固定写法,没什么好说的。

那么如何将字符串格式的时间转换成time.Time呢?下面两个函数会比较经常使用到:

A)

t, _ := time.Parse("2006-01-02 15:04:05", "2017-04-25 09:14:00")

这里咱们发现,t:=time.Now()返回的时间是time.Time,上面这行代码也是time.Time可是打印出来的结果:

2017-04-25 16:15:11.235733 +0800 CST

2016-06-13 09:14:00 +0000 UTC

为何会不同呢?缘由是 time.Now() 的时区是 time.Local,而 time.Parse 解析出来的时区倒是 time.UTC(能够经过 Time.Location() 函数知道是哪一个时区)。在中国,它们相差 8 小时。

因此,通常的,咱们应该老是使用 time.ParseInLocation 来解析时间,并给第三个参数传递 time.Local:

t, _ := time.ParseInLocation("2006-01-02 15:04:05", "2017-04-25 16:14:00", time.Local)

以前项目中遇到要获取某个时间以前的最近整点时间,这个时候有几种办法:

t, _ := time.ParseInLocation("2006-01-02 15:04:05", time.Now().Format("2006-01-02 15:00:00"), time.Local)

 

t, _ := time.ParseInLocation("2006-01-02 15:04:05", "2016-06-13 15:34:39", time.Local)

t0:=t.Truncate(1 * time.Hour)

相关文章
相关标签/搜索