SoFunction
Updated on 2025-03-05

How to use golang time, time zone, format

A few days ago, due to the need to achieve regular downtime on overseas servers, the concept of time zone was involved. I searched online and found that most of them are the Layouts in talks, which are very unsystematic. Here I will briefly summarize the time initialization, time zone conversion and format conversion.

During development, we use time more frequently. According to the probability of use, from large to small, usually:

  1. Get the current or database storage time
  2. Compare the order of two time points
  3. Show print time
  4. Time zone conversion

Corresponding to go, that is, several basic definitions:

  1. Time point and time period: Time, Duration. Like M in MVC.
  2. Time zone: Location, in time conversion, it is like C in MVC.
  3. Format: Format layout definition, like V in MVC.

There is nothing to talk about on Duration alone, it is very simple to use. Add and Sub in Time instance are related to it and are very easy to get started, so I won’t say more.

Time zone

Time zone is a very important concept for time calculation, and it is particularly emphasized that it is two completely different concepts from layout. Go language uses Location as a running instance of time zones. When converting it to different time zones at the same time needs to be carried out through different locations. By default, UTC (unix standard time) is used instead of GMT (GMT) of the past tense.

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

  now := ()
  local1, err1 := ("") //Equivalent to "UTC"  if err1 != nil {
    (err1)
  }
  local2, err2 := ("Local")//The time zone set by the server  if err2 != nil {
    (err2)
  }
  local3, err3 := ("America/Los_Angeles")
  if err3 != nil {
    (err3)
  }

  ((local1))
  ((local2))
  ((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

In the code, except for the "UTC" and "Local" that can be seen in the source code of the function, the other values ​​actually follow the rules of "IANA Time Zone". You can decompress the $GOROOT/lib/time/ file to open and view. In this directory of Asia, I saw Chongqing, Hong_Kong, but no Beijing. To obtain Beijing time in China abroad, you need to use "PRC", of course "Asia/Chongqing" is also a method:

loc, _:= ("Asia/Chongqing")  //The parameters are the "directory" + "/" + "file name" of the decompressed file.(().In(loc))

It is worth emphasizing that Location is only used for time zone conversion and does not affect the data inside the time (it is actually the Unix standard internally). Therefore, when several time instances add and sub, there is no need to pay attention to whether the Location is the same.

Time formatting

In the previous example, the print result is very ugly, and no one usually cares about ns after seconds; after defining the time zone, the time difference with UTC is rarely needed. At this time, we need to define our layout.

Many people on the Internet say, "2006-01-02 15:04:05 is the birth time of go, so designing Format's Layout in this way should not be true. Please see the table below:

01/Jan 02 03/15 04 05 06 -07[00][:00] PM Mon
moon day hour point Second Year jet lag Morning What day of the week

That is, 1234567, corresponding to: month, day, hour, minute, second, year, time difference, easy to remember. Just a little attention:

  • Month: 01 or Jan can
  • Hours: 03 means 12-hour system, 15 means 24-hour system.
  • Time difference: It is -07, not 07, "00" or ":00" can be added later to indicate a further minute and second time difference.
  • Day and afternoon: Use PM, not AM.
  • Placement order: random, even repeat. Source code packages also have commonly defined formats for use.

Perhaps because the corresponding "year" of 2006 is about the same time as the project launch of Go, there are misinformation online. In the source code time/, there is a very clear description. If you paste it, you won't translate it:

// These are predefined layouts for use in and .
// 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 has provided 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"
)

But my personal habit is still "2006-01-02 15:04:05 Mon". The previous code was slightly modified, and that's it:

  formate:="2006-01-02 15:04:05 Mon"
  now := ()
  local1, err1 := ("UTC") //Input parameter "UTC", equivalent to ""  if err1 != nil {
    (err1)
  }
  local2, err2 := ("Local")
  if err2 != nil {
    (err2)
  }
  local3, err3 := ("America/Los_Angeles")
  if err3 != nil {
    (err3)
  }

  ((local1).Format(formate))
  ((local2).Format(formate))
  ((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 commonly used, go also provides initialization through unix standard time and strings:

//Use string, default UTC time zone initialization Timefunc Parse(layout, value string) (Time, error) 
//Initialize Time by specifying the time zone by stringfunc ParseInLocation(layout, value string, loc *Location) (Time, error) 

//Initialize Time via Unix Standard Timefunc Unix(sec int64, nsec int64) Time 

When initializing time, be sure to pay attention to the time zone of the original input value. I happened to have a variable in my hand, "2016-11-28 19:36:25" local time in Los Angeles, and the unix time is accurate to 1480390585 seconds. The code that parses it is as follows:

  local, _ := ("America/Los_Angeles")
  timeFormat := "2006-01-02 15:04:05"
  //func Unix(sec int64, nsec int64) Time {
  time1 := (1480390585, 0)                           //Set time through the seconds and nanoseconds of unix standard time  time2, _ := (timeFormat, "2016-11-28 19:36:25", local) //Los Angeles time  ((local).Format(timeFormat))
  ((local).Format(timeFormat))
  chinaLocal, _ := ("Local")//When running, the server must be set to the Chinese time zone, otherwise it is best to use specific parameters such as "Asia/Chongqing".  ((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 and has a time zone

“2016-12-04 15:39:06 +0800 CST”

There is no need to use the ParseInLocation method, just use Parse directly.

Of course, there are many functions in other time packages, but there are already many descriptions on the Internet, so I won’t talk about them anymore.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.