golang time time zone format usage

  • 2020-07-21 08:21:28
  • OfStack

A few days ago, due to the need to realize the overseas server scheduled outage, involving the concept of the time zone. I searched 1 on the Internet, and most of them talked about Layout in time.Format, which is very unsystematic. Here I simply summarized the time initialization, time zone conversion and format conversion in 1.

In development, we use a lot of time, and its application scenarios, from large to small according to the probability of use, are usually:

Gets the time currently stored in the database Compare two points in time Display print time Time zone conversion

Corresponding to go, namely several basic definitions:

Point and time: Time,Duration. Like M in MVC. Time zone: Location, equivalent to C in time conversion. Formatting: layout definition of Format, as V in MVC.

There is nothing to talk about about Duration alone, and it is very simple to use. Add and Sub in the Time instance are related to it and are very easy to learn, so I won't say more about them.

The time zone

Time zone is a very important concept for time computing, and it is emphasized that it is a completely different concept from layout. The go language is used by Location as a running instance of a time zone, and conversion to a different time zone at time 1 requires a different Location. By default, UTC (unix STANDARD time) is used instead of the past form GMT (Greenwich Mean time).

The following code shows the conversion of UTC, Beijing, and Los Angeles at the same time:


  now := time.Now()
  local1, err1 := time.LoadLocation("") // Is equivalent to "UTC"
  if err1 != nil {
    fmt.Println(err1)
  }
  local2, err2 := time.LoadLocation("Local")// The time zone set by the server 
  if err2 != nil {
    fmt.Println(err2)
  }
  local3, err3 := time.LoadLocation("America/Los_Angeles")
  if err3 != nil {
    fmt.Println(err3)
  }

  fmt.Println(now.In(local1))
  fmt.Println(now.In(local2))
  fmt.Println(now.In(local3))
  //output:
  //2016-12-04 07:39:06.270473069 +0000 UTC
  //2016-12-04 15:39:06.270473069 +0800 CST
  //2016-12-03 23:39:06.270473069 -0800 PST

Code, LoadLocation input parameter values, in addition to the function of the source code can be seen in the "Local UTC", "", the rest of the value is in accordance with the" IANA Time Zone "rules, can extract the $GOROOT lib/time/zoneinfo zip open view this file. In the directory Asia, I see Chongqing, Hong_Kong, but no Beijing. PRC is used to obtain Beijing Time in foreign countries. Of course, Asia/Chongqing is also used:


loc, _:= time.LoadLocation("Asia/Chongqing")  // The parameter is the directory of the unzipped file + " / " + File name. 
fmt.Println(time.Now().In(loc))

It is worth emphasizing that Location is only used for time zone conversion and does not affect the data inside time (which is actually the unix standard inside), so when several time instances are performing Add and Sub, it is not necessary to pay attention to whether Location is the same or not.

Time formatting

In the previous example, the print is so ugly that no one usually CARES about ns seconds later; With a clear time zone, the time difference with UTC is rarely needed. At this point, we need to define layout.

Many of the online claims that "2006-01-02 15:04:05 is the birth date of go, so the design of Layout in this way" should not be true. See the following table:

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

It is 1234567, corresponding to the time difference of month, day, minute, second and year respectively, which is very good memory. Just pay a little attention to 1:

Month: 01 or Jan is ok Hours: 03 means 12 hours, 15 means 24 hours. Time difference: -07, not 07, after the can be added "00" or ":00", more than one step of the time difference. Last afternoon: PM, not AM. Order: Random or even repetitive. The source code package also has a defined common format for use.

Perhaps because the "year" corresponding to '06 was similar to the start time of go's project, online misinformation emerged. time/ ES102en. go source code, there is a very clear description, paste 1, will not be translated:

[

// 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

]

Although go already provides more than 10 common formats:


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

However, my personal habit is still "2006-01-02 15:04:05 Mon". With a little modification, the code looks like this:


  formate:="2006-01-02 15:04:05 Mon"
  now := time.Now()
  local1, err1 := time.LoadLocation("UTC") // The input parameters "UTC" Is the same as ""
  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

Time initialization

In addition to the most common ES132en. Now, go also provides two ways to initialize via unix standard time and string:


// By string, default UTC Time zone initialization Time
func Parse(layout, value string) (Time, error) 
// Class by string, specifying the time zone Time
func ParseInLocation(layout, value string, loc *Location) (Time, error) 

// through unix  Standard time initialization Time
func Unix(sec int64, nsec int64) Time 

When the time is initialized, pay attention to the time zone of the original input value. It happens to have a variable in hand, "2016-11-28 19:36:25" local time in Los Angeles, unix time accurate to 1480390585. The code that resolves it is as follows:


  local, _ := time.LoadLocation("America/Los_Angeles")
  timeFormat := "2006-01-02 15:04:05"
  //func Unix(sec int64, nsec int64) Time {
  time1 := time.Unix(1480390585, 0)                           // through unix Seconds in standard time, nanoseconds to set the time 
  time2, _ := time.ParseInLocation(timeFormat, "2016-11-28 19:36:25", local) // Los Angeles time 
  fmt.Println(time1.In(local).Format(timeFormat))
  fmt.Println(time2.In(local).Format(timeFormat))
  chinaLocal, _ := time.LoadLocation("Local")// At runtime, the server must be set to the China time zone, otherwise it is best to adopt "Asia/Chongqing" And so on. 
  fmt.Println(time2.In(chinaLocal).Format(timeFormat))
  //output:
  //2016-11-28 19:36:25
  //2016-11-28 19:36:25
  //2016-11-29 11:36:25

Of course, if the input value is a string with a time zone

[

"The 2016-12-04 15:39:06 + 0800 CST"

]

It is not necessary to use ParseInLocation method, but Parse.

Of course, there are many other functions in the time package, but there are already plenty of descriptions on the web that are no longer verbose.


Related articles: