Go - Representing Time Zones

发布时间 2023-10-05 16:19:55作者: ZhangZhihuiAAA

Problem: You want to include the time zone information in a Time struct.


Solution: The Time struct includes a Location , which is the representation of the time zone.

 

A time zone is an area that follows a standard time that roughly follows longitude but in practice tends to follow political boundaries. All time zones are defined as offsets of the Coordinated Universal Time (UTC), ranging from UTC - 12:00 to UTC+14:00.

The Location struct in the time package represents a time zone. Go’s time package, like many other libraries in different programming languages, uses the time zone database managed by the Internet Assigned Numbers Authority (IANA).

This database, also known as tz or zoneinfo , contains data for many locations around the world, and the latest as of this writing is 28 March 2023. The naming convention for time zones in the tz database is in the form of Area/Location , for example Asia/Singapore or America/New_York .

There are a few ways to create a Location struct. First, you can use LoadLocation (loading the location from the tz database):

func   main ()   { 
      location ,   err   :=   time . LoadLocation ( "Asia/Singapore" ) 
      if   err   !=   nil   { 
          log . Println ( "Cannot  load  location:" ,   err ) 
      } 
      fmt . Println ( "location:" ,   location ) 
      utcTime   :=   time . Date ( 2009 ,   time . November ,   10 ,   23 ,   0 ,   0 ,   0 ,   time . UTC ) 
      fmt . Println ( "UTC  time:" ,   utcTime ) 
      fmt . Println ( "equivalent  in  Singapore:" ,   utcTime . In ( location )) 
}

This is what you should see:

location:  Asia/Singapore
UTC  time:  2009 - 11 - 10  23:00:00  +0000  UTC
equivalent  in  Singapore:  2009 - 11 - 11  07:00:00  +0800  +08

You can see that the name of the time zone is just 08 instead of Asia/Singapore . Lo⁠adLoc⁠ati⁠on simply loads the location from the tz database that’s in the computer it’s running on. If you want to use different data, you can use the LoadLocationFromTZData function instead.

Another way of creating a Location is to use the FixedZone function. This allows you to create any location you want (without being in the tz database) and also name it whatever you want:

func   main ()   { 
      location   :=   time . FixedZone ( "Singapore  Time" ,   8 * 60 * 60 ) 
      fmt . Println ( "location:" ,   location ) 
      utcTime   :=   time . Date ( 2009 ,   time . November ,   10 ,   23 ,   0 ,   0 ,   0 ,   time . UTC ) 
      fmt . Println ( "UTC  time:" ,   utcTime ) 
      fmt . Println ( "equivalent  in  Singapore:" ,   utcTime . In ( location )) 
}

This is what you should see:

location: Singapore Time
UTC time: 2009 - 11 - 10 23:00:00 +0000 UTC
equivalent in Singapore: 2009 - 11 - 11 07:00:00 +0800 Singapore Time

As you can see, the name of the time zone is now Singapore Time.