Black Lives Matter. Support the Equal Justice Initiative.

Source file src/time/zoneinfo.go

Documentation: time

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package time
     6  
     7  import (
     8  	"errors"
     9  	"sync"
    10  	"syscall"
    11  )
    12  
    13  //go:generate env ZONEINFO=$GOROOT/lib/time/zoneinfo.zip go run genzabbrs.go -output zoneinfo_abbrs_windows.go
    14  
    15  // A Location maps time instants to the zone in use at that time.
    16  // Typically, the Location represents the collection of time offsets
    17  // in use in a geographical area. For many Locations the time offset varies
    18  // depending on whether daylight savings time is in use at the time instant.
    19  type Location struct {
    20  	name string
    21  	zone []zone
    22  	tx   []zoneTrans
    23  
    24  	// The tzdata information can be followed by a string that describes
    25  	// how to handle DST transitions not recorded in zoneTrans.
    26  	// The format is the TZ environment variable without a colon; see
    27  	// https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html.
    28  	// Example string, for America/Los_Angeles: PST8PDT,M3.2.0,M11.1.0
    29  	extend string
    30  
    31  	// Most lookups will be for the current time.
    32  	// To avoid the binary search through tx, keep a
    33  	// static one-element cache that gives the correct
    34  	// zone for the time when the Location was created.
    35  	// if cacheStart <= t < cacheEnd,
    36  	// lookup can return cacheZone.
    37  	// The units for cacheStart and cacheEnd are seconds
    38  	// since January 1, 1970 UTC, to match the argument
    39  	// to lookup.
    40  	cacheStart int64
    41  	cacheEnd   int64
    42  	cacheZone  *zone
    43  }
    44  
    45  // A zone represents a single time zone such as CET.
    46  type zone struct {
    47  	name   string // abbreviated name, "CET"
    48  	offset int    // seconds east of UTC
    49  	isDST  bool   // is this zone Daylight Savings Time?
    50  }
    51  
    52  // A zoneTrans represents a single time zone transition.
    53  type zoneTrans struct {
    54  	when         int64 // transition time, in seconds since 1970 GMT
    55  	index        uint8 // the index of the zone that goes into effect at that time
    56  	isstd, isutc bool  // ignored - no idea what these mean
    57  }
    58  
    59  // alpha and omega are the beginning and end of time for zone
    60  // transitions.
    61  const (
    62  	alpha = -1 << 63  // math.MinInt64
    63  	omega = 1<<63 - 1 // math.MaxInt64
    64  )
    65  
    66  // UTC represents Universal Coordinated Time (UTC).
    67  var UTC *Location = &utcLoc
    68  
    69  // utcLoc is separate so that get can refer to &utcLoc
    70  // and ensure that it never returns a nil *Location,
    71  // even if a badly behaved client has changed UTC.
    72  var utcLoc = Location{name: "UTC"}
    73  
    74  // Local represents the system's local time zone.
    75  // On Unix systems, Local consults the TZ environment
    76  // variable to find the time zone to use. No TZ means
    77  // use the system default /etc/localtime.
    78  // TZ="" means use UTC.
    79  // TZ="foo" means use file foo in the system timezone directory.
    80  var Local *Location = &localLoc
    81  
    82  // localLoc is separate so that initLocal can initialize
    83  // it even if a client has changed Local.
    84  var localLoc Location
    85  var localOnce sync.Once
    86  
    87  func (l *Location) get() *Location {
    88  	if l == nil {
    89  		return &utcLoc
    90  	}
    91  	if l == &localLoc {
    92  		localOnce.Do(initLocal)
    93  	}
    94  	return l
    95  }
    96  
    97  // String returns a descriptive name for the time zone information,
    98  // corresponding to the name argument to LoadLocation or FixedZone.
    99  func (l *Location) String() string {
   100  	return l.get().name
   101  }
   102  
   103  // FixedZone returns a Location that always uses
   104  // the given zone name and offset (seconds east of UTC).
   105  func FixedZone(name string, offset int) *Location {
   106  	l := &Location{
   107  		name:       name,
   108  		zone:       []zone{{name, offset, false}},
   109  		tx:         []zoneTrans{{alpha, 0, false, false}},
   110  		cacheStart: alpha,
   111  		cacheEnd:   omega,
   112  	}
   113  	l.cacheZone = &l.zone[0]
   114  	return l
   115  }
   116  
   117  // lookup returns information about the time zone in use at an
   118  // instant in time expressed as seconds since January 1, 1970 00:00:00 UTC.
   119  //
   120  // The returned information gives the name of the zone (such as "CET"),
   121  // the start and end times bracketing sec when that zone is in effect,
   122  // the offset in seconds east of UTC (such as -5*60*60), and whether
   123  // the daylight savings is being observed at that time.
   124  func (l *Location) lookup(sec int64) (name string, offset int, start, end int64) {
   125  	l = l.get()
   126  
   127  	if len(l.zone) == 0 {
   128  		name = "UTC"
   129  		offset = 0
   130  		start = alpha
   131  		end = omega
   132  		return
   133  	}
   134  
   135  	if zone := l.cacheZone; zone != nil && l.cacheStart <= sec && sec < l.cacheEnd {
   136  		name = zone.name
   137  		offset = zone.offset
   138  		start = l.cacheStart
   139  		end = l.cacheEnd
   140  		return
   141  	}
   142  
   143  	if len(l.tx) == 0 || sec < l.tx[0].when {
   144  		zone := &l.zone[l.lookupFirstZone()]
   145  		name = zone.name
   146  		offset = zone.offset
   147  		start = alpha
   148  		if len(l.tx) > 0 {
   149  			end = l.tx[0].when
   150  		} else {
   151  			end = omega
   152  		}
   153  		return
   154  	}
   155  
   156  	// Binary search for entry with largest time <= sec.
   157  	// Not using sort.Search to avoid dependencies.
   158  	tx := l.tx
   159  	end = omega
   160  	lo := 0
   161  	hi := len(tx)
   162  	for hi-lo > 1 {
   163  		m := lo + (hi-lo)/2
   164  		lim := tx[m].when
   165  		if sec < lim {
   166  			end = lim
   167  			hi = m
   168  		} else {
   169  			lo = m
   170  		}
   171  	}
   172  	zone := &l.zone[tx[lo].index]
   173  	name = zone.name
   174  	offset = zone.offset
   175  	start = tx[lo].when
   176  	// end = maintained during the search
   177  
   178  	// If we're at the end of the known zone transitions,
   179  	// try the extend string.
   180  	if lo == len(tx)-1 && l.extend != "" {
   181  		if ename, eoffset, estart, eend, _, ok := tzset(l.extend, end, sec); ok {
   182  			return ename, eoffset, estart, eend
   183  		}
   184  	}
   185  
   186  	return
   187  }
   188  
   189  // lookupFirstZone returns the index of the time zone to use for times
   190  // before the first transition time, or when there are no transition
   191  // times.
   192  //
   193  // The reference implementation in localtime.c from
   194  // https://www.iana.org/time-zones/repository/releases/tzcode2013g.tar.gz
   195  // implements the following algorithm for these cases:
   196  // 1) If the first zone is unused by the transitions, use it.
   197  // 2) Otherwise, if there are transition times, and the first
   198  //    transition is to a zone in daylight time, find the first
   199  //    non-daylight-time zone before and closest to the first transition
   200  //    zone.
   201  // 3) Otherwise, use the first zone that is not daylight time, if
   202  //    there is one.
   203  // 4) Otherwise, use the first zone.
   204  func (l *Location) lookupFirstZone() int {
   205  	// Case 1.
   206  	if !l.firstZoneUsed() {
   207  		return 0
   208  	}
   209  
   210  	// Case 2.
   211  	if len(l.tx) > 0 && l.zone[l.tx[0].index].isDST {
   212  		for zi := int(l.tx[0].index) - 1; zi >= 0; zi-- {
   213  			if !l.zone[zi].isDST {
   214  				return zi
   215  			}
   216  		}
   217  	}
   218  
   219  	// Case 3.
   220  	for zi := range l.zone {
   221  		if !l.zone[zi].isDST {
   222  			return zi
   223  		}
   224  	}
   225  
   226  	// Case 4.
   227  	return 0
   228  }
   229  
   230  // firstZoneUsed reports whether the first zone is used by some
   231  // transition.
   232  func (l *Location) firstZoneUsed() bool {
   233  	for _, tx := range l.tx {
   234  		if tx.index == 0 {
   235  			return true
   236  		}
   237  	}
   238  	return false
   239  }
   240  
   241  // tzset takes a timezone string like the one found in the TZ environment
   242  // variable, the end of the last time zone transition expressed as seconds
   243  // since January 1, 1970 00:00:00 UTC, and a time expressed the same way.
   244  // We call this a tzset string since in C the function tzset reads TZ.
   245  // The return values are as for lookup, plus ok which reports whether the
   246  // parse succeeded.
   247  func tzset(s string, initEnd, sec int64) (name string, offset int, start, end int64, isDST, ok bool) {
   248  	var (
   249  		stdName, dstName     string
   250  		stdOffset, dstOffset int
   251  	)
   252  
   253  	stdName, s, ok = tzsetName(s)
   254  	if ok {
   255  		stdOffset, s, ok = tzsetOffset(s)
   256  	}
   257  	if !ok {
   258  		return "", 0, 0, 0, false, false
   259  	}
   260  
   261  	// The numbers in the tzset string are added to local time to get UTC,
   262  	// but our offsets are added to UTC to get local time,
   263  	// so we negate the number we see here.
   264  	stdOffset = -stdOffset
   265  
   266  	if len(s) == 0 || s[0] == ',' {
   267  		// No daylight savings time.
   268  		return stdName, stdOffset, initEnd, omega, false, true
   269  	}
   270  
   271  	dstName, s, ok = tzsetName(s)
   272  	if ok {
   273  		if len(s) == 0 || s[0] == ',' {
   274  			dstOffset = stdOffset + secondsPerHour
   275  		} else {
   276  			dstOffset, s, ok = tzsetOffset(s)
   277  			dstOffset = -dstOffset // as with stdOffset, above
   278  		}
   279  	}
   280  	if !ok {
   281  		return "", 0, 0, 0, false, false
   282  	}
   283  
   284  	if len(s) == 0 {
   285  		// Default DST rules per tzcode.
   286  		s = ",M3.2.0,M11.1.0"
   287  	}
   288  	// The TZ definition does not mention ';' here but tzcode accepts it.
   289  	if s[0] != ',' && s[0] != ';' {
   290  		return "", 0, 0, 0, false, false
   291  	}
   292  	s = s[1:]
   293  
   294  	var startRule, endRule rule
   295  	startRule, s, ok = tzsetRule(s)
   296  	if !ok || len(s) == 0 || s[0] != ',' {
   297  		return "", 0, 0, 0, false, false
   298  	}
   299  	s = s[1:]
   300  	endRule, s, ok = tzsetRule(s)
   301  	if !ok || len(s) > 0 {
   302  		return "", 0, 0, 0, false, false
   303  	}
   304  
   305  	year, _, _, yday := absDate(uint64(sec+unixToInternal+internalToAbsolute), false)
   306  
   307  	ysec := int64(yday*secondsPerDay) + sec%secondsPerDay
   308  
   309  	// Compute start of year in seconds since Unix epoch.
   310  	d := daysSinceEpoch(year)
   311  	abs := int64(d * secondsPerDay)
   312  	abs += absoluteToInternal + internalToUnix
   313  
   314  	startSec := int64(tzruleTime(year, startRule, stdOffset))
   315  	endSec := int64(tzruleTime(year, endRule, dstOffset))
   316  	dstIsDST, stdIsDST := true, false
   317  	// Note: this is a flipping of "DST" and "STD" while retaining the labels
   318  	// This happens in southern hemispheres. The labelling here thus is a little
   319  	// inconsistent with the goal.
   320  	if endSec < startSec {
   321  		startSec, endSec = endSec, startSec
   322  		stdName, dstName = dstName, stdName
   323  		stdOffset, dstOffset = dstOffset, stdOffset
   324  		stdIsDST, dstIsDST = dstIsDST, stdIsDST
   325  	}
   326  
   327  	// The start and end values that we return are accurate
   328  	// close to a daylight savings transition, but are otherwise
   329  	// just the start and end of the year. That suffices for
   330  	// the only caller that cares, which is Date.
   331  	if ysec < startSec {
   332  		return stdName, stdOffset, abs, startSec + abs, stdIsDST, true
   333  	} else if ysec >= endSec {
   334  		return stdName, stdOffset, endSec + abs, abs + 365*secondsPerDay, stdIsDST, true
   335  	} else {
   336  		return dstName, dstOffset, startSec + abs, endSec + abs, dstIsDST, true
   337  	}
   338  }
   339  
   340  // tzsetName returns the timezone name at the start of the tzset string s,
   341  // and the remainder of s, and reports whether the parsing is OK.
   342  func tzsetName(s string) (string, string, bool) {
   343  	if len(s) == 0 {
   344  		return "", "", false
   345  	}
   346  	if s[0] != '<' {
   347  		for i, r := range s {
   348  			switch r {
   349  			case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ',', '-', '+':
   350  				if i < 3 {
   351  					return "", "", false
   352  				}
   353  				return s[:i], s[i:], true
   354  			}
   355  		}
   356  		if len(s) < 3 {
   357  			return "", "", false
   358  		}
   359  		return s, "", true
   360  	} else {
   361  		for i, r := range s {
   362  			if r == '>' {
   363  				return s[1:i], s[i+1:], true
   364  			}
   365  		}
   366  		return "", "", false
   367  	}
   368  }
   369  
   370  // tzsetOffset returns the timezone offset at the start of the tzset string s,
   371  // and the remainder of s, and reports whether the parsing is OK.
   372  // The timezone offset is returned as a number of seconds.
   373  func tzsetOffset(s string) (offset int, rest string, ok bool) {
   374  	if len(s) == 0 {
   375  		return 0, "", false
   376  	}
   377  	neg := false
   378  	if s[0] == '+' {
   379  		s = s[1:]
   380  	} else if s[0] == '-' {
   381  		s = s[1:]
   382  		neg = true
   383  	}
   384  
   385  	// The tzdata code permits values up to 24 * 7 here,
   386  	// although POSIX does not.
   387  	var hours int
   388  	hours, s, ok = tzsetNum(s, 0, 24*7)
   389  	if !ok {
   390  		return 0, "", false
   391  	}
   392  	off := hours * secondsPerHour
   393  	if len(s) == 0 || s[0] != ':' {
   394  		if neg {
   395  			off = -off
   396  		}
   397  		return off, s, true
   398  	}
   399  
   400  	var mins int
   401  	mins, s, ok = tzsetNum(s[1:], 0, 59)
   402  	if !ok {
   403  		return 0, "", false
   404  	}
   405  	off += mins * secondsPerMinute
   406  	if len(s) == 0 || s[0] != ':' {
   407  		if neg {
   408  			off = -off
   409  		}
   410  		return off, s, true
   411  	}
   412  
   413  	var secs int
   414  	secs, s, ok = tzsetNum(s[1:], 0, 59)
   415  	if !ok {
   416  		return 0, "", false
   417  	}
   418  	off += secs
   419  
   420  	if neg {
   421  		off = -off
   422  	}
   423  	return off, s, true
   424  }
   425  
   426  // ruleKind is the kinds of rules that can be seen in a tzset string.
   427  type ruleKind int
   428  
   429  const (
   430  	ruleJulian ruleKind = iota
   431  	ruleDOY
   432  	ruleMonthWeekDay
   433  )
   434  
   435  // rule is a rule read from a tzset string.
   436  type rule struct {
   437  	kind ruleKind
   438  	day  int
   439  	week int
   440  	mon  int
   441  	time int // transition time
   442  }
   443  
   444  // tzsetRule parses a rule from a tzset string.
   445  // It returns the rule, and the remainder of the string, and reports success.
   446  func tzsetRule(s string) (rule, string, bool) {
   447  	var r rule
   448  	if len(s) == 0 {
   449  		return rule{}, "", false
   450  	}
   451  	ok := false
   452  	if s[0] == 'J' {
   453  		var jday int
   454  		jday, s, ok = tzsetNum(s[1:], 1, 365)
   455  		if !ok {
   456  			return rule{}, "", false
   457  		}
   458  		r.kind = ruleJulian
   459  		r.day = jday
   460  	} else if s[0] == 'M' {
   461  		var mon int
   462  		mon, s, ok = tzsetNum(s[1:], 1, 12)
   463  		if !ok || len(s) == 0 || s[0] != '.' {
   464  			return rule{}, "", false
   465  
   466  		}
   467  		var week int
   468  		week, s, ok = tzsetNum(s[1:], 1, 5)
   469  		if !ok || len(s) == 0 || s[0] != '.' {
   470  			return rule{}, "", false
   471  		}
   472  		var day int
   473  		day, s, ok = tzsetNum(s[1:], 0, 6)
   474  		if !ok {
   475  			return rule{}, "", false
   476  		}
   477  		r.kind = ruleMonthWeekDay
   478  		r.day = day
   479  		r.week = week
   480  		r.mon = mon
   481  	} else {
   482  		var day int
   483  		day, s, ok = tzsetNum(s, 0, 365)
   484  		if !ok {
   485  			return rule{}, "", false
   486  		}
   487  		r.kind = ruleDOY
   488  		r.day = day
   489  	}
   490  
   491  	if len(s) == 0 || s[0] != '/' {
   492  		r.time = 2 * secondsPerHour // 2am is the default
   493  		return r, s, true
   494  	}
   495  
   496  	offset, s, ok := tzsetOffset(s[1:])
   497  	if !ok {
   498  		return rule{}, "", false
   499  	}
   500  	r.time = offset
   501  
   502  	return r, s, true
   503  }
   504  
   505  // tzsetNum parses a number from a tzset string.
   506  // It returns the number, and the remainder of the string, and reports success.
   507  // The number must be between min and max.
   508  func tzsetNum(s string, min, max int) (num int, rest string, ok bool) {
   509  	if len(s) == 0 {
   510  		return 0, "", false
   511  	}
   512  	num = 0
   513  	for i, r := range s {
   514  		if r < '0' || r > '9' {
   515  			if i == 0 || num < min {
   516  				return 0, "", false
   517  			}
   518  			return num, s[i:], true
   519  		}
   520  		num *= 10
   521  		num += int(r) - '0'
   522  		if num > max {
   523  			return 0, "", false
   524  		}
   525  	}
   526  	if num < min {
   527  		return 0, "", false
   528  	}
   529  	return num, "", true
   530  }
   531  
   532  // tzruleTime takes a year, a rule, and a timezone offset,
   533  // and returns the number of seconds since the start of the year
   534  // that the rule takes effect.
   535  func tzruleTime(year int, r rule, off int) int {
   536  	var s int
   537  	switch r.kind {
   538  	case ruleJulian:
   539  		s = (r.day - 1) * secondsPerDay
   540  		if isLeap(year) && r.day >= 60 {
   541  			s += secondsPerDay
   542  		}
   543  	case ruleDOY:
   544  		s = r.day * secondsPerDay
   545  	case ruleMonthWeekDay:
   546  		// Zeller's Congruence.
   547  		m1 := (r.mon+9)%12 + 1
   548  		yy0 := year
   549  		if r.mon <= 2 {
   550  			yy0--
   551  		}
   552  		yy1 := yy0 / 100
   553  		yy2 := yy0 % 100
   554  		dow := ((26*m1-2)/10 + 1 + yy2 + yy2/4 + yy1/4 - 2*yy1) % 7
   555  		if dow < 0 {
   556  			dow += 7
   557  		}
   558  		// Now dow is the day-of-week of the first day of r.mon.
   559  		// Get the day-of-month of the first "dow" day.
   560  		d := r.day - dow
   561  		if d < 0 {
   562  			d += 7
   563  		}
   564  		for i := 1; i < r.week; i++ {
   565  			if d+7 >= daysIn(Month(r.mon), year) {
   566  				break
   567  			}
   568  			d += 7
   569  		}
   570  		d += int(daysBefore[r.mon-1])
   571  		if isLeap(year) && r.mon > 2 {
   572  			d++
   573  		}
   574  		s = d * secondsPerDay
   575  	}
   576  
   577  	return s + r.time - off
   578  }
   579  
   580  // lookupName returns information about the time zone with
   581  // the given name (such as "EST") at the given pseudo-Unix time
   582  // (what the given time of day would be in UTC).
   583  func (l *Location) lookupName(name string, unix int64) (offset int, ok bool) {
   584  	l = l.get()
   585  
   586  	// First try for a zone with the right name that was actually
   587  	// in effect at the given time. (In Sydney, Australia, both standard
   588  	// and daylight-savings time are abbreviated "EST". Using the
   589  	// offset helps us pick the right one for the given time.
   590  	// It's not perfect: during the backward transition we might pick
   591  	// either one.)
   592  	for i := range l.zone {
   593  		zone := &l.zone[i]
   594  		if zone.name == name {
   595  			nam, offset, _, _ := l.lookup(unix - int64(zone.offset))
   596  			if nam == zone.name {
   597  				return offset, true
   598  			}
   599  		}
   600  	}
   601  
   602  	// Otherwise fall back to an ordinary name match.
   603  	for i := range l.zone {
   604  		zone := &l.zone[i]
   605  		if zone.name == name {
   606  			return zone.offset, true
   607  		}
   608  	}
   609  
   610  	// Otherwise, give up.
   611  	return
   612  }
   613  
   614  // NOTE(rsc): Eventually we will need to accept the POSIX TZ environment
   615  // syntax too, but I don't feel like implementing it today.
   616  
   617  var errLocation = errors.New("time: invalid location name")
   618  
   619  var zoneinfo *string
   620  var zoneinfoOnce sync.Once
   621  
   622  // LoadLocation returns the Location with the given name.
   623  //
   624  // If the name is "" or "UTC", LoadLocation returns UTC.
   625  // If the name is "Local", LoadLocation returns Local.
   626  //
   627  // Otherwise, the name is taken to be a location name corresponding to a file
   628  // in the IANA Time Zone database, such as "America/New_York".
   629  //
   630  // The time zone database needed by LoadLocation may not be
   631  // present on all systems, especially non-Unix systems.
   632  // LoadLocation looks in the directory or uncompressed zip file
   633  // named by the ZONEINFO environment variable, if any, then looks in
   634  // known installation locations on Unix systems,
   635  // and finally looks in $GOROOT/lib/time/zoneinfo.zip.
   636  func LoadLocation(name string) (*Location, error) {
   637  	if name == "" || name == "UTC" {
   638  		return UTC, nil
   639  	}
   640  	if name == "Local" {
   641  		return Local, nil
   642  	}
   643  	if containsDotDot(name) || name[0] == '/' || name[0] == '\\' {
   644  		// No valid IANA Time Zone name contains a single dot,
   645  		// much less dot dot. Likewise, none begin with a slash.
   646  		return nil, errLocation
   647  	}
   648  	zoneinfoOnce.Do(func() {
   649  		env, _ := syscall.Getenv("ZONEINFO")
   650  		zoneinfo = &env
   651  	})
   652  	var firstErr error
   653  	if *zoneinfo != "" {
   654  		if zoneData, err := loadTzinfoFromDirOrZip(*zoneinfo, name); err == nil {
   655  			if z, err := LoadLocationFromTZData(name, zoneData); err == nil {
   656  				return z, nil
   657  			}
   658  			firstErr = err
   659  		} else if err != syscall.ENOENT {
   660  			firstErr = err
   661  		}
   662  	}
   663  	if z, err := loadLocation(name, zoneSources); err == nil {
   664  		return z, nil
   665  	} else if firstErr == nil {
   666  		firstErr = err
   667  	}
   668  	return nil, firstErr
   669  }
   670  
   671  // containsDotDot reports whether s contains "..".
   672  func containsDotDot(s string) bool {
   673  	if len(s) < 2 {
   674  		return false
   675  	}
   676  	for i := 0; i < len(s)-1; i++ {
   677  		if s[i] == '.' && s[i+1] == '.' {
   678  			return true
   679  		}
   680  	}
   681  	return false
   682  }
   683  

View as plain text