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, 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
   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, 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
   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
   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
   298  	}
   299  	s = s[1:]
   300  	endRule, s, ok = tzsetRule(s)
   301  	if !ok || len(s) > 0 {
   302  		return "", 0, 0, 0, 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  	if endSec < startSec {
   317  		startSec, endSec = endSec, startSec
   318  		stdName, dstName = dstName, stdName
   319  		stdOffset, dstOffset = dstOffset, stdOffset
   320  	}
   321  
   322  	// The start and end values that we return are accurate
   323  	// close to a daylight savings transition, but are otherwise
   324  	// just the start and end of the year. That suffices for
   325  	// the only caller that cares, which is Date.
   326  	if ysec < startSec {
   327  		return stdName, stdOffset, abs, startSec + abs, true
   328  	} else if ysec >= endSec {
   329  		return stdName, stdOffset, endSec + abs, abs + 365*secondsPerDay, true
   330  	} else {
   331  		return dstName, dstOffset, startSec + abs, endSec + abs, true
   332  	}
   333  }
   334  
   335  // tzsetName returns the timezone name at the start of the tzset string s,
   336  // and the remainder of s, and reports whether the parsing is OK.
   337  func tzsetName(s string) (string, string, bool) {
   338  	if len(s) == 0 {
   339  		return "", "", false
   340  	}
   341  	if s[0] != '<' {
   342  		for i, r := range s {
   343  			switch r {
   344  			case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ',', '-', '+':
   345  				if i < 3 {
   346  					return "", "", false
   347  				}
   348  				return s[:i], s[i:], true
   349  			}
   350  		}
   351  		if len(s) < 3 {
   352  			return "", "", false
   353  		}
   354  		return s, "", true
   355  	} else {
   356  		for i, r := range s {
   357  			if r == '>' {
   358  				return s[1:i], s[i+1:], true
   359  			}
   360  		}
   361  		return "", "", false
   362  	}
   363  }
   364  
   365  // tzsetOffset returns the timezone offset at the start of the tzset string s,
   366  // and the remainder of s, and reports whether the parsing is OK.
   367  // The timezone offset is returned as a number of seconds.
   368  func tzsetOffset(s string) (offset int, rest string, ok bool) {
   369  	if len(s) == 0 {
   370  		return 0, "", false
   371  	}
   372  	neg := false
   373  	if s[0] == '+' {
   374  		s = s[1:]
   375  	} else if s[0] == '-' {
   376  		s = s[1:]
   377  		neg = true
   378  	}
   379  
   380  	var hours int
   381  	hours, s, ok = tzsetNum(s, 0, 24)
   382  	if !ok {
   383  		return 0, "", false
   384  	}
   385  	off := hours * secondsPerHour
   386  	if len(s) == 0 || s[0] != ':' {
   387  		if neg {
   388  			off = -off
   389  		}
   390  		return off, s, true
   391  	}
   392  
   393  	var mins int
   394  	mins, s, ok = tzsetNum(s[1:], 0, 59)
   395  	if !ok {
   396  		return 0, "", false
   397  	}
   398  	off += mins * secondsPerMinute
   399  	if len(s) == 0 || s[0] != ':' {
   400  		if neg {
   401  			off = -off
   402  		}
   403  		return off, s, true
   404  	}
   405  
   406  	var secs int
   407  	secs, s, ok = tzsetNum(s[1:], 0, 59)
   408  	if !ok {
   409  		return 0, "", false
   410  	}
   411  	off += secs
   412  
   413  	if neg {
   414  		off = -off
   415  	}
   416  	return off, s, true
   417  }
   418  
   419  // ruleKind is the kinds of rules that can be seen in a tzset string.
   420  type ruleKind int
   421  
   422  const (
   423  	ruleJulian ruleKind = iota
   424  	ruleDOY
   425  	ruleMonthWeekDay
   426  )
   427  
   428  // rule is a rule read from a tzset string.
   429  type rule struct {
   430  	kind ruleKind
   431  	day  int
   432  	week int
   433  	mon  int
   434  	time int // transition time
   435  }
   436  
   437  // tzsetRule parses a rule from a tzset string.
   438  // It returns the rule, and the remainder of the string, and reports success.
   439  func tzsetRule(s string) (rule, string, bool) {
   440  	var r rule
   441  	if len(s) == 0 {
   442  		return rule{}, "", false
   443  	}
   444  	ok := false
   445  	if s[0] == 'J' {
   446  		var jday int
   447  		jday, s, ok = tzsetNum(s[1:], 1, 365)
   448  		if !ok {
   449  			return rule{}, "", false
   450  		}
   451  		r.kind = ruleJulian
   452  		r.day = jday
   453  	} else if s[0] == 'M' {
   454  		var mon int
   455  		mon, s, ok = tzsetNum(s[1:], 1, 12)
   456  		if !ok || len(s) == 0 || s[0] != '.' {
   457  			return rule{}, "", false
   458  
   459  		}
   460  		var week int
   461  		week, s, ok = tzsetNum(s[1:], 1, 5)
   462  		if !ok || len(s) == 0 || s[0] != '.' {
   463  			return rule{}, "", false
   464  		}
   465  		var day int
   466  		day, s, ok = tzsetNum(s[1:], 0, 6)
   467  		if !ok {
   468  			return rule{}, "", false
   469  		}
   470  		r.kind = ruleMonthWeekDay
   471  		r.day = day
   472  		r.week = week
   473  		r.mon = mon
   474  	} else {
   475  		var day int
   476  		day, s, ok = tzsetNum(s, 0, 365)
   477  		if !ok {
   478  			return rule{}, "", false
   479  		}
   480  		r.kind = ruleDOY
   481  		r.day = day
   482  	}
   483  
   484  	if len(s) == 0 || s[0] != '/' {
   485  		r.time = 2 * secondsPerHour // 2am is the default
   486  		return r, s, true
   487  	}
   488  
   489  	offset, s, ok := tzsetOffset(s[1:])
   490  	if !ok || offset < 0 {
   491  		return rule{}, "", false
   492  	}
   493  	r.time = offset
   494  
   495  	return r, s, true
   496  }
   497  
   498  // tzsetNum parses a number from a tzset string.
   499  // It returns the number, and the remainder of the string, and reports success.
   500  // The number must be between min and max.
   501  func tzsetNum(s string, min, max int) (num int, rest string, ok bool) {
   502  	if len(s) == 0 {
   503  		return 0, "", false
   504  	}
   505  	num = 0
   506  	for i, r := range s {
   507  		if r < '0' || r > '9' {
   508  			if i == 0 || num < min {
   509  				return 0, "", false
   510  			}
   511  			return num, s[i:], true
   512  		}
   513  		num *= 10
   514  		num += int(r) - '0'
   515  		if num > max {
   516  			return 0, "", false
   517  		}
   518  	}
   519  	if num < min {
   520  		return 0, "", false
   521  	}
   522  	return num, "", true
   523  }
   524  
   525  // tzruleTime takes a year, a rule, and a timezone offset,
   526  // and returns the number of seconds since the start of the year
   527  // that the rule takes effect.
   528  func tzruleTime(year int, r rule, off int) int {
   529  	var s int
   530  	switch r.kind {
   531  	case ruleJulian:
   532  		s = (r.day - 1) * secondsPerDay
   533  		if isLeap(year) && r.day >= 60 {
   534  			s += secondsPerDay
   535  		}
   536  	case ruleDOY:
   537  		s = r.day * secondsPerDay
   538  	case ruleMonthWeekDay:
   539  		// Zeller's Congruence.
   540  		m1 := (r.mon+9)%12 + 1
   541  		yy0 := year
   542  		if r.mon <= 2 {
   543  			yy0--
   544  		}
   545  		yy1 := yy0 / 100
   546  		yy2 := yy0 % 100
   547  		dow := ((26*m1-2)/10 + 1 + yy2 + yy2/4 + yy1/4 - 2*yy1) % 7
   548  		if dow < 0 {
   549  			dow += 7
   550  		}
   551  		// Now dow is the day-of-week of the first day of r.mon.
   552  		// Get the day-of-month of the first "dow" day.
   553  		d := r.day - dow
   554  		if d < 0 {
   555  			d += 7
   556  		}
   557  		for i := 1; i < r.week; i++ {
   558  			if d+7 >= daysIn(Month(r.mon), year) {
   559  				break
   560  			}
   561  			d += 7
   562  		}
   563  		d += int(daysBefore[r.mon-1])
   564  		if isLeap(year) && r.mon > 2 {
   565  			d++
   566  		}
   567  		s = d * secondsPerDay
   568  	}
   569  
   570  	return s + r.time - off
   571  }
   572  
   573  // lookupName returns information about the time zone with
   574  // the given name (such as "EST") at the given pseudo-Unix time
   575  // (what the given time of day would be in UTC).
   576  func (l *Location) lookupName(name string, unix int64) (offset int, ok bool) {
   577  	l = l.get()
   578  
   579  	// First try for a zone with the right name that was actually
   580  	// in effect at the given time. (In Sydney, Australia, both standard
   581  	// and daylight-savings time are abbreviated "EST". Using the
   582  	// offset helps us pick the right one for the given time.
   583  	// It's not perfect: during the backward transition we might pick
   584  	// either one.)
   585  	for i := range l.zone {
   586  		zone := &l.zone[i]
   587  		if zone.name == name {
   588  			nam, offset, _, _ := l.lookup(unix - int64(zone.offset))
   589  			if nam == zone.name {
   590  				return offset, true
   591  			}
   592  		}
   593  	}
   594  
   595  	// Otherwise fall back to an ordinary name match.
   596  	for i := range l.zone {
   597  		zone := &l.zone[i]
   598  		if zone.name == name {
   599  			return zone.offset, true
   600  		}
   601  	}
   602  
   603  	// Otherwise, give up.
   604  	return
   605  }
   606  
   607  // NOTE(rsc): Eventually we will need to accept the POSIX TZ environment
   608  // syntax too, but I don't feel like implementing it today.
   609  
   610  var errLocation = errors.New("time: invalid location name")
   611  
   612  var zoneinfo *string
   613  var zoneinfoOnce sync.Once
   614  
   615  // LoadLocation returns the Location with the given name.
   616  //
   617  // If the name is "" or "UTC", LoadLocation returns UTC.
   618  // If the name is "Local", LoadLocation returns Local.
   619  //
   620  // Otherwise, the name is taken to be a location name corresponding to a file
   621  // in the IANA Time Zone database, such as "America/New_York".
   622  //
   623  // The time zone database needed by LoadLocation may not be
   624  // present on all systems, especially non-Unix systems.
   625  // LoadLocation looks in the directory or uncompressed zip file
   626  // named by the ZONEINFO environment variable, if any, then looks in
   627  // known installation locations on Unix systems,
   628  // and finally looks in $GOROOT/lib/time/zoneinfo.zip.
   629  func LoadLocation(name string) (*Location, error) {
   630  	if name == "" || name == "UTC" {
   631  		return UTC, nil
   632  	}
   633  	if name == "Local" {
   634  		return Local, nil
   635  	}
   636  	if containsDotDot(name) || name[0] == '/' || name[0] == '\\' {
   637  		// No valid IANA Time Zone name contains a single dot,
   638  		// much less dot dot. Likewise, none begin with a slash.
   639  		return nil, errLocation
   640  	}
   641  	zoneinfoOnce.Do(func() {
   642  		env, _ := syscall.Getenv("ZONEINFO")
   643  		zoneinfo = &env
   644  	})
   645  	var firstErr error
   646  	if *zoneinfo != "" {
   647  		if zoneData, err := loadTzinfoFromDirOrZip(*zoneinfo, name); err == nil {
   648  			if z, err := LoadLocationFromTZData(name, zoneData); err == nil {
   649  				return z, nil
   650  			}
   651  			firstErr = err
   652  		} else if err != syscall.ENOENT {
   653  			firstErr = err
   654  		}
   655  	}
   656  	if z, err := loadLocation(name, zoneSources); err == nil {
   657  		return z, nil
   658  	} else if firstErr == nil {
   659  		firstErr = err
   660  	}
   661  	return nil, firstErr
   662  }
   663  
   664  // containsDotDot reports whether s contains "..".
   665  func containsDotDot(s string) bool {
   666  	if len(s) < 2 {
   667  		return false
   668  	}
   669  	for i := 0; i < len(s)-1; i++ {
   670  		if s[i] == '.' && s[i+1] == '.' {
   671  			return true
   672  		}
   673  	}
   674  	return false
   675  }
   676  

View as plain text