golang 时间格式化总结

根据字符串创建一个基于当地时区的时间类型

通过Date.now方法获取的是基于当地时区的时间

 

now := Date.now() 

结果是2019-06-27 10:28:31.282649389 +0800 CST m=+0.000347190,注意是带了当地时区+08的

通过time.Parse将字符串转化为时间类型,是UTC时间

 

before, _:= time.Parse("2006-01-02 15:04:05", "2019-06-26 22:06:00")

结果是 2019-06-26 22:06:00 +0000 UTC

其实我想做的是,将2019-06-26 22:06:00转化为东八区的时间,应该用time.ParseInLocation方法

 

local, _:=time.ParseInLocation("2006-01-02 15:04:05", "2019-06-26 20:00:00", time.Local)
// 2019-06-26 22:06:00 +0800 CST

将当地时区转化为UTC时间

 

// local根据上一步创建的是 2019-06-26 22:06:00 +0800 CST
utcLocal :=local.UTC()

结果是2019-06-26 14:06:00 +0000 UTC,转化为UTC时间自动-8小时。

将UTC时间转化为当地时间

 

local2 :=utcLocal.Local()

结果是2019-06-26 22:06:00 +0800 CST

golang还提供了更多的格式化参考格式提供选择
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"
)

你可能感兴趣的:(Golang)