golang时间、时区、格式的使用方法

2020-01-28 13:45:35于海丽

网上好多都说,“2006-01-02 15:04:05是go的诞生时间,所以这么设计Format的Layout”,应该不是真的。请看下表:

01/Jan 02 03/15 04 05 06 -07[00][:00] PM Mon
时差 上下午 星期几

也就是1234567,分别对应:月日时分秒年 时差,很好记忆。只是稍微注意一下:

月:01或Jan都可以 小时:03表示12小时制,15表示24小时制。 时差:是 -07 ,不是 07,后边可以增加“00”或“:00”,表示更进一步的分秒时差。 上下午:使用PM,不是AM。 摆放顺序:随意,甚至重复都可以。源代码包也有定义的常用格式供使用。

也许是因为06对应的“年”与go的项目启动时间差不多,也就有了网上的误传。在源代码time/time.go中,有非常明确的描述,粘贴一下,就不翻译了:

// These are predefined layouts for use in Time.Format and Time.Parse.
// The reference time used in the layouts is the specific time:
// Mon Jan 2 15:04:05 MST 2006
// which is Unix time 1136239445. Since MST is GMT-0700,
// the reference time can be thought of as
// 01/02 03:04:05PM ‘06 -0700

虽然go已经提供了10多个常用格式:


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"
)

但个人习惯还是“2006-01-02 15:04:05 Mon”,之前代码稍加修改,就是这样:


  formate:="2006-01-02 15:04:05 Mon"
  now := time.Now()
  local1, err1 := time.LoadLocation("UTC") //输入参数"UTC",等同于""
  if err1 != nil {
    fmt.Println(err1)
  }
  local2, err2 := time.LoadLocation("Local")
  if err2 != nil {
    fmt.Println(err2)
  }
  local3, err3 := time.LoadLocation("America/Los_Angeles")
  if err3 != nil {
    fmt.Println(err3)
  }

  fmt.Println(now.In(local1).Format(formate))
  fmt.Println(now.In(local2).Format(formate))
  fmt.Println(now.In(local3).Format(formate))
  //output:
  //2016-12-04 08:06:39 Sun
  //2016-12-04 16:06:39 Sun
  //2016-12-04 00:06:39 Sun