golang package time的用法具体详解

2020-01-28 13:08:50于丽

在我们编程过程中,经常会用到与时间相关的各种务需求,下面来介绍 golang 中有关时间的一些基本用法,我们从 time 的几种 type 来开始介绍。

时间可分为时间点与时间段, golang 也不例外,提供了以下两种基础类型

    时间点(Time) 时间段(Duration)

除此之外 golang 也提供了以下类型,做一些特定的业务

    时区(Location) Ticker Timer(定时器)

我们将按以上顺序来介绍 time 包的使用。

时间点(Time)

我们使用的所有与时间相关的业务都是基于点而延伸的,两点组成一个时间段,大多数应用也都是围绕这些点与面去做逻辑处理。

初始化

go 针对不同的参数类型提供了以下初始化的方式


// func Now() Time
 fmt.Println(time.Now())

 // func Parse(layout, value string) (Time, error)
 time.Parse("2016-01-02 15:04:05", "2018-04-23 12:24:51")

 // func ParseInLocation(layout, value string, loc *Location) (Time, error) (layout已带时区时可直接用Parse)
 time.ParseInLocation("2006-01-02 15:04:05", "2017-05-11 14:06:06", time.Local)

 // func Unix(sec int64, nsec int64) Time
 time.Unix(1e9, 0)

 // func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
 time.Date(2018, 1, 2, 15, 30, 10, 0, time.Local)

 // func (t Time) In(loc *Location) Time 当前时间对应指定时区的时间
 loc, _ := time.LoadLocation("America/Los_Angeles")
 fmt.Println(time.Now().In(loc))

 // func (t Time) Local() Time

获取到时间点之后为了满足业务和设计,需要转换成我们需要的格式,也就是所谓的时间格式化。

格式化

to string

格式化为字符串我们需要使用 time.Format 方法来转换成我们想要的格式


fmt.Println(time.Now().Format("2006-01-02 15:04:05")) // 2018-04-24 10:11:20
 fmt.Println(time.Now().Format(time.UnixDate))  // Tue Apr 24 09:59:02 CST 2018

Format 函数中可以指定你想使用的格式,同时 time 包中也给了一些我们常用的格式


const (
 ANSIC = "Mon Jan _2 15:04:05 2006"
 UnixDate = "Mon Jan _2 15:04:05 MST 2006"
 RubyDate = "Mon Jan 02 15:04:05 -0700 2006"
 RFC822 = "02 Jan 06 15:04 MST"
 RFC822Z = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
 RFC850 = "Monday, 02-Jan-06 15:04:05 MST"
 RFC1123 = "Mon, 02 Jan 2006 15:04:05 MST"
 RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
 RFC3339 = "2006-01-02T15:04:05Z07:00"
 RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
 Kitchen = "3:04PM"
 // Handy time stamps.
 Stamp = "Jan _2 15:04:05"
 StampMilli = "Jan _2 15:04:05.000"
 StampMicro = "Jan _2 15:04:05.000000"
 StampNano = "Jan _2 15:04:05.000000000"
)

注意: galang 中指定的 特定时间格式 为 "2006-01-02 15:04:05 -0700 MST" , 为了记忆方便,按照美式时间格式 月日时分秒年 外加时区 排列起来依次 是 01/02 03:04:05PM ‘06 -0700 ,刚开始使用时需要注意。