美文网首页
go 中的时间相关处理

go 中的时间相关处理

作者: wayyyy | 来源:发表于2022-05-03 00:19 被阅读0次

时区

GMT(Greenwich Mean Time),格林威治平时。GMT 根据地球的自转和公转来计算时间,它规定太阳每天经过位于英国伦敦郊区的皇家格林威治天文台的时间为中午12点。GMT 是前世界标准时。

UTC(Coordinated Universal Time),协调世界时。UTC 比 GMT 更精准,它根据原子钟来计算时间。在不需要精确到秒的情况下,可以认为 UTC=GMT。UTC 是现世界标准时。

从格林威治本初子午线起,往东为正,往西为负,全球共划分为 24 个标准时区,相邻时区相差一个小时。

time.Time

time 库,最核心的对象是 time.Time 结构体。它的定义如下,用以表示某个瞬间的时间。

type Time struct {
   wall uint64
   ext  int64
   loc *Location
}

计算机在时间处理上,主要涉及到两种时钟:

  • 墙上时钟(wall time),又称为钟表时间,用于表示具体的日期与时间。

  • 单调时钟(monotonic clocks),总是保证时间是向前的,不会出现墙上时钟的回拨问题,因此它很适合用于测量持续时间段。

wallext 字段就是用于记录墙上时钟和单调时钟,精度为纳秒。
loc 字段记录时区位置,当 loc 为 nil 时,默认为 UTC 时间

获取 time.Time

可以通过 Now 函数获取当前本地时间

func Now() Time

也可以通过 Date 函数,根据年、月、日等时间和时区参数获取指定时间

func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
和时间戳互转

计算机世界中,将 UTC 时间 1970 年1月1日 0 时 0 分 0 秒作为 Unix 时间 0。所谓的时间瞬间转换为 Unix 时间戳,即计算的是从 Unix 时间 0 到指定瞬间所经过的秒数、微秒数等。

func (t Time) Unix() int64       // 从 Unix 时间 0 经过的秒数
func (t Time) UnixMicro() int64  // 从 Unix 时间 0 经过的微秒数
func (t Time) UnixMilli() int64  // 从 Unix 时间 0 经过的毫秒数
func (t Time) UnixNano() int64   // 从 Unix 时间 0 经过的纳秒数

时间戳和 time.Time 互转:

time.Unix(1668233682, 0)
获取基本字段
 t := time.Now()
 fmt.Println(t.Date())      // 2022 July 17
 fmt.Println(t.Year())      // 2022
 fmt.Println(t.Month())     // July
 fmt.Println(t.ISOWeek())   // 2022 28
 fmt.Println(t.Clock())     // 22 21 56
 fmt.Println(t.Day())       // 17
 fmt.Println(t.Weekday())   // Sunday
 fmt.Println(t.Hour())      // 22
 fmt.Println(t.Minute())    // 21
 fmt.Println(t.Second())    // 56
 fmt.Println(t.Nanosecond())// 494313000
 fmt.Println(t.YearDay())   // 198
时区转换

如果需要获取同一个 time.Time 在不同时区下的结果,我们可以使用它的 In 方法。

now := time.Now()
fmt.Println(now)   // 2022-07-18 21:19:59.9636 +0800 CST m=+0.000069242

loc, _ := time.LoadLocation("UTC")
fmt.Println(now.In(loc)) // 2022-07-18 13:19:59.9636 +0000 UTC
格式化时间

Go 使用固定的时间(需要注意,使用其他的时间是不可以的)作为布局模板,而这个固定时间是 Go 语言的诞生时间Mon Jan 2 15:04:05 MST 2006

// 用于将 time.Time 对象根据给定的布局转换为时间字符串。
func (t Time) Format(layout string) string 

func main() {
    currentTime := time.Now()

    fmt.Println("1、当前时间  : ", currentTime)
    fmt.Println("2、当前时间字符串: ", currentTime.String())
    fmt.Println("3、MM-DD-YYYY : ", currentTime.Format("01-02-2006"))
    fmt.Println("4、YYYY-MM-DD : ", currentTime.Format("2006-01-02"))
    fmt.Println("5、YYYY.MM.DD : ", currentTime.Format("2006.01.02 15:04:05"))
    fmt.Println("6、YYYY#MM#DD {Special Character} : ", currentTime.Format("2006#01#02"))
    fmt.Println("7、YYYY-MM-DD hh:mm:ss : ", currentTime.Format("2006-01-02 15:04:05"))
    fmt.Println("8、Time with MicroSeconds: ", currentTime.Format("2006-01-02 15:04:05.000000"))
    fmt.Println("9、Time with NanoSeconds: ", currentTime.Format("2006-01-02 15:04:05.000000000"))
    fmt.Println("10、ShortNum Month : ", currentTime.Format("2006-1-02"))
    fmt.Println("11、LongMonth : ", currentTime.Format("2006-January-02"))
    fmt.Println("12、ShortMonth : ", currentTime.Format("2006-Jan-02"))
    fmt.Println("13、ShortYear : ", currentTime.Format("06-Jan-02"))
    fmt.Println("14、LongWeekDay : ", currentTime.Format("2006-01-02 15:04:05 Monday"))
    fmt.Println("15、ShortWeek Day : ", currentTime.Format("2006-01-02 Mon"))
    fmt.Println("16、ShortDay : ", currentTime.Format("Mon 2006-01-2"))
    fmt.Println("17、Short Hour Minute Second: ", currentTime.Format("2006-01-02 3:4:5"))
    fmt.Println("18、Short Hour Minute Second: ", currentTime.Format("2006-01-02 3:4:5 PM"))
    fmt.Println("19、Short Hour Minute Second: ", currentTime.Format("2006-01-02 3:4:5 pm"))
}
image.png

如果需要将格式化时间转为 time.Time,那么需要:

// 用于将时间字符串根据它所能对应的布局转换为 time.Time 对象
func Parse(layout, value string) (Time, error) 

const (
    layoutISO = "2006-01-02"
    layoutUS  = "January 2, 2006"
)

func main() {
    date := "2012-08-09"
    t, _ := time.Parse(layoutISO, date)
    fmt.Println(t)                  // 2012-08-09 00:00:00 +0000 UTC
    fmt.Println(t.Format(layoutUS)) // August 9, 2012
}

在 time 库中提供了一些预定义的布局模板常量,这些可以直接拿来使用:

const (
 Layout      = "01/02 03:04:05PM '06 -0700" // The reference time, in numerical order.
 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"
)

time.Duration

time.Duration 用于表示两个时间瞬间 time.Time 之间所经过的时间。它通过 int64 表示纳秒计数,能表示的极限大约为 290 年。

Go 的 time 包中定义了这些持续时间常量值:

const (
    Nanosecond  Duration = 1
    Microsecond          = 1000 * Nanosecond
    Millisecond          = 1000 * Microsecond
    Second               = 1000 * Millisecond
    Minute               = 60 * Second
    Hour                 = 60 * Minute
)

同时,time.Duration 提供了能获取各时间粒度数值的方法:

func (d Duration) Nanoseconds() int64    // 纳秒
func (d Duration) Microseconds() int64   // 微秒
func (d Duration) Milliseconds() int64   // 毫秒
func (d Duration) Seconds() float64      // 秒
func (d Duration) Minutes() float64      // 分钟
func (d Duration) Hours() float64        // 小时
时间计算

Add 函数用于增加/减少( d 的正值表示增加、负值表示减少) time.Time 的持续时间。我们可以对某瞬时时间,增加或减少指定纳秒级以上的时间。

func (t Time) Add(d Duration) Time 

AddDate 函数基于年、月和日的维度增加/减少 time.Time 的值。

func (t Time) AddDate(years int, months int, days int) Time

Sub 函数可以得出两个时间瞬间之间的持续时间

func (t Time) Sub(u Time) Duration

基于当前时间瞬间 time.Now() 的计算是最普遍的需求。因此,time 包还提供了以下便捷的时间计算函数。

func Since(t Time) Duration  // 等同于 time.Now().Sub(t) 
func Until(t Time) Duration   // 等同于 t.Sub(time.Now()) 

使用:

 t := time.Now()
 fmt.Println(t)                      // 2022-07-17 22:41:06.001567 +0800 CST m=+0.000057466

 //时间增加 1小时
 fmt.Println(t.Add(time.Hour * 1))   // 2022-07-17 23:41:06.001567 +0800 CST m=+3600.000057466
 //时间增加 15 分钟
 fmt.Println(t.Add(time.Minute * 15))// 2022-07-17 22:56:06.001567 +0800 CST m=+900.000057466
 //时间增加 10 秒钟
 fmt.Println(t.Add(time.Second * 10))// 2022-07-17 22:41:16.001567 +0800 CST m=+10.000057466

 //时间减少 1 小时
 fmt.Println(t.Add(-time.Hour * 1))  // 2022-07-17 21:41:06.001567 +0800 CST m=-3599.999942534
 //时间减少 15 分钟
 fmt.Println(t.Add(-time.Minute * 15))// 2022-07-17 22:26:06.001567 +0800 CST m=-899.999942534
 //时间减少 10 秒钟
 fmt.Println(t.Add(-time.Second * 10))// 2022-07-17 22:40:56.001567 +0800 CST m=-9.999942534

 time.Sleep(time.Second * 5)
 t2 := time.Now()
 // 计算 t 到 t2 的持续时间
 fmt.Println(t2.Sub(t))              // 5.004318874s
 // 1 年之后的时间
 t3 := t2.AddDate(1, 0, 0)
 // 计算从 t 到当前的持续时间
 fmt.Println(time.Since(t))          // 5.004442316s
 // 计算现在到明年的持续时间
 fmt.Println(time.Until(t3))         // 8759h59m59.999864s

相关文章

  • go 中的时间相关处理

    时区 GMT(Greenwich Mean Time),格林威治平时。GMT 根据地球的自转和公转来计算时间,它规...

  • pandas中时间相关的处理

    一、将时间差转化为秒 1、Dataframe里面,要转换一整列的数值时,使用apply。这种方式可能有点慢,但由于...

  • go时间处理

    推荐一个非常优秀的包 github.com/jinzhu/now 基本用法 使用中遇到时区问题 以上代码输出时区不...

  • 时间的相关处理!

    NSDate+Extension.h: #import@interface NSDate (Extension) ...

  • 时间处理相关杂记

    时间间隔timedelta的扩展使用 我们在处理时间间隔的时候,肯定都使用过timedelta进行时间的加减。 但...

  • 时间处理相关方法

    Date nowdate = new Date(); 一个过时方法 -----------------------...

  • 基础-3

    异常处理 error接口:Go中的一个关于错误处理的标准模式,属于Go内建的接口类型;type error int...

  • 今日coding随记

    今天晚上学了go语言,通过浏览印象笔记中记的相关笔记,还仔细阅读了陈皓极客时间和他coolshell的相关文章。然...

  • golang异常处理机制panic-defer-recover

    Go中的Exception处理采用什么机制? 一句话总结: Go中可以抛出一个panic的异常,然后在defer中...

  • Java中 使用 Date 和 SimpleDateFormat

    使用 Date 和 SimpleDateFormat 类表示时间 在程序开发中,经常需要处理日期和时间的相关数据,...

网友评论

      本文标题:go 中的时间相关处理

      本文链接:https://www.haomeiwen.com/subject/remyyrtx.html