Source file src/time/time.go

     1  // Copyright 2009 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 provides functionality for measuring and displaying time.
     6  //
     7  // The calendrical calculations always assume a Gregorian calendar, with
     8  // no leap seconds.
     9  //
    10  // Monotonic Clocks
    11  //
    12  // Operating systems provide both a “wall clock,” which is subject to
    13  // changes for clock synchronization, and a “monotonic clock,” which is
    14  // not. The general rule is that the wall clock is for telling time and
    15  // the monotonic clock is for measuring time. Rather than split the API,
    16  // in this package the Time returned by time.Now contains both a wall
    17  // clock reading and a monotonic clock reading; later time-telling
    18  // operations use the wall clock reading, but later time-measuring
    19  // operations, specifically comparisons and subtractions, use the
    20  // monotonic clock reading.
    21  //
    22  // For example, this code always computes a positive elapsed time of
    23  // approximately 20 milliseconds, even if the wall clock is changed during
    24  // the operation being timed:
    25  //
    26  //	start := time.Now()
    27  //	... operation that takes 20 milliseconds ...
    28  //	t := time.Now()
    29  //	elapsed := t.Sub(start)
    30  //
    31  // Other idioms, such as time.Since(start), time.Until(deadline), and
    32  // time.Now().Before(deadline), are similarly robust against wall clock
    33  // resets.
    34  //
    35  // The rest of this section gives the precise details of how operations
    36  // use monotonic clocks, but understanding those details is not required
    37  // to use this package.
    38  //
    39  // The Time returned by time.Now contains a monotonic clock reading.
    40  // If Time t has a monotonic clock reading, t.Add adds the same duration to
    41  // both the wall clock and monotonic clock readings to compute the result.
    42  // Because t.AddDate(y, m, d), t.Round(d), and t.Truncate(d) are wall time
    43  // computations, they always strip any monotonic clock reading from their results.
    44  // Because t.In, t.Local, and t.UTC are used for their effect on the interpretation
    45  // of the wall time, they also strip any monotonic clock reading from their results.
    46  // The canonical way to strip a monotonic clock reading is to use t = t.Round(0).
    47  //
    48  // If Times t and u both contain monotonic clock readings, the operations
    49  // t.After(u), t.Before(u), t.Equal(u), and t.Sub(u) are carried out
    50  // using the monotonic clock readings alone, ignoring the wall clock
    51  // readings. If either t or u contains no monotonic clock reading, these
    52  // operations fall back to using the wall clock readings.
    53  //
    54  // On some systems the monotonic clock will stop if the computer goes to sleep.
    55  // On such a system, t.Sub(u) may not accurately reflect the actual
    56  // time that passed between t and u.
    57  //
    58  // Because the monotonic clock reading has no meaning outside
    59  // the current process, the serialized forms generated by t.GobEncode,
    60  // t.MarshalBinary, t.MarshalJSON, and t.MarshalText omit the monotonic
    61  // clock reading, and t.Format provides no format for it. Similarly, the
    62  // constructors time.Date, time.Parse, time.ParseInLocation, and time.Unix,
    63  // as well as the unmarshalers t.GobDecode, t.UnmarshalBinary.
    64  // t.UnmarshalJSON, and t.UnmarshalText always create times with
    65  // no monotonic clock reading.
    66  //
    67  // Note that the Go == operator compares not just the time instant but
    68  // also the Location and the monotonic clock reading. See the
    69  // documentation for the Time type for a discussion of equality
    70  // testing for Time values.
    71  //
    72  // For debugging, the result of t.String does include the monotonic
    73  // clock reading if present. If t != u because of different monotonic clock readings,
    74  // that difference will be visible when printing t.String() and u.String().
    75  //
    76  package time
    77  
    78  import (
    79  	"errors"
    80  	_ "unsafe" // for go:linkname
    81  )
    82  
    83  // A Time represents an instant in time with nanosecond precision.
    84  //
    85  // Programs using times should typically store and pass them as values,
    86  // not pointers. That is, time variables and struct fields should be of
    87  // type time.Time, not *time.Time.
    88  //
    89  // A Time value can be used by multiple goroutines simultaneously except
    90  // that the methods GobDecode, UnmarshalBinary, UnmarshalJSON and
    91  // UnmarshalText are not concurrency-safe.
    92  //
    93  // Time instants can be compared using the Before, After, and Equal methods.
    94  // The Sub method subtracts two instants, producing a Duration.
    95  // The Add method adds a Time and a Duration, producing a Time.
    96  //
    97  // The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC.
    98  // As this time is unlikely to come up in practice, the IsZero method gives
    99  // a simple way of detecting a time that has not been initialized explicitly.
   100  //
   101  // Each Time has associated with it a Location, consulted when computing the
   102  // presentation form of the time, such as in the Format, Hour, and Year methods.
   103  // The methods Local, UTC, and In return a Time with a specific location.
   104  // Changing the location in this way changes only the presentation; it does not
   105  // change the instant in time being denoted and therefore does not affect the
   106  // computations described in earlier paragraphs.
   107  //
   108  // Representations of a Time value saved by the GobEncode, MarshalBinary,
   109  // MarshalJSON, and MarshalText methods store the Time.Location's offset, but not
   110  // the location name. They therefore lose information about Daylight Saving Time.
   111  //
   112  // In addition to the required “wall clock” reading, a Time may contain an optional
   113  // reading of the current process's monotonic clock, to provide additional precision
   114  // for comparison or subtraction.
   115  // See the “Monotonic Clocks” section in the package documentation for details.
   116  //
   117  // Note that the Go == operator compares not just the time instant but also the
   118  // Location and the monotonic clock reading. Therefore, Time values should not
   119  // be used as map or database keys without first guaranteeing that the
   120  // identical Location has been set for all values, which can be achieved
   121  // through use of the UTC or Local method, and that the monotonic clock reading
   122  // has been stripped by setting t = t.Round(0). In general, prefer t.Equal(u)
   123  // to t == u, since t.Equal uses the most accurate comparison available and
   124  // correctly handles the case when only one of its arguments has a monotonic
   125  // clock reading.
   126  //
   127  type Time struct {
   128  	// wall and ext encode the wall time seconds, wall time nanoseconds,
   129  	// and optional monotonic clock reading in nanoseconds.
   130  	//
   131  	// From high to low bit position, wall encodes a 1-bit flag (hasMonotonic),
   132  	// a 33-bit seconds field, and a 30-bit wall time nanoseconds field.
   133  	// The nanoseconds field is in the range [0, 999999999].
   134  	// If the hasMonotonic bit is 0, then the 33-bit field must be zero
   135  	// and the full signed 64-bit wall seconds since Jan 1 year 1 is stored in ext.
   136  	// If the hasMonotonic bit is 1, then the 33-bit field holds a 33-bit
   137  	// unsigned wall seconds since Jan 1 year 1885, and ext holds a
   138  	// signed 64-bit monotonic clock reading, nanoseconds since process start.
   139  	wall uint64
   140  	ext  int64
   141  
   142  	// loc specifies the Location that should be used to
   143  	// determine the minute, hour, month, day, and year
   144  	// that correspond to this Time.
   145  	// The nil location means UTC.
   146  	// All UTC times are represented with loc==nil, never loc==&utcLoc.
   147  	loc *Location
   148  }
   149  
   150  const (
   151  	hasMonotonic = 1 << 63
   152  	maxWall      = wallToInternal + (1<<33 - 1) // year 2157
   153  	minWall      = wallToInternal               // year 1885
   154  	nsecMask     = 1<<30 - 1
   155  	nsecShift    = 30
   156  )
   157  
   158  // These helpers for manipulating the wall and monotonic clock readings
   159  // take pointer receivers, even when they don't modify the time,
   160  // to make them cheaper to call.
   161  
   162  // nsec returns the time's nanoseconds.
   163  func (t *Time) nsec() int32 {
   164  	return int32(t.wall & nsecMask)
   165  }
   166  
   167  // sec returns the time's seconds since Jan 1 year 1.
   168  func (t *Time) sec() int64 {
   169  	if t.wall&hasMonotonic != 0 {
   170  		return wallToInternal + int64(t.wall<<1>>(nsecShift+1))
   171  	}
   172  	return t.ext
   173  }
   174  
   175  // unixSec returns the time's seconds since Jan 1 1970 (Unix time).
   176  func (t *Time) unixSec() int64 { return t.sec() + internalToUnix }
   177  
   178  // addSec adds d seconds to the time.
   179  func (t *Time) addSec(d int64) {
   180  	if t.wall&hasMonotonic != 0 {
   181  		sec := int64(t.wall << 1 >> (nsecShift + 1))
   182  		dsec := sec + d
   183  		if 0 <= dsec && dsec <= 1<<33-1 {
   184  			t.wall = t.wall&nsecMask | uint64(dsec)<<nsecShift | hasMonotonic
   185  			return
   186  		}
   187  		// Wall second now out of range for packed field.
   188  		// Move to ext.
   189  		t.stripMono()
   190  	}
   191  
   192  	// Check if the sum of t.ext and d overflows and handle it properly.
   193  	sum := t.ext + d
   194  	if (sum > t.ext) == (d > 0) {
   195  		t.ext = sum
   196  	} else if d > 0 {
   197  		t.ext = 1<<63 - 1
   198  	} else {
   199  		t.ext = -(1<<63 - 1)
   200  	}
   201  }
   202  
   203  // setLoc sets the location associated with the time.
   204  func (t *Time) setLoc(loc *Location) {
   205  	if loc == &utcLoc {
   206  		loc = nil
   207  	}
   208  	t.stripMono()
   209  	t.loc = loc
   210  }
   211  
   212  // stripMono strips the monotonic clock reading in t.
   213  func (t *Time) stripMono() {
   214  	if t.wall&hasMonotonic != 0 {
   215  		t.ext = t.sec()
   216  		t.wall &= nsecMask
   217  	}
   218  }
   219  
   220  // setMono sets the monotonic clock reading in t.
   221  // If t cannot hold a monotonic clock reading,
   222  // because its wall time is too large,
   223  // setMono is a no-op.
   224  func (t *Time) setMono(m int64) {
   225  	if t.wall&hasMonotonic == 0 {
   226  		sec := t.ext
   227  		if sec < minWall || maxWall < sec {
   228  			return
   229  		}
   230  		t.wall |= hasMonotonic | uint64(sec-minWall)<<nsecShift
   231  	}
   232  	t.ext = m
   233  }
   234  
   235  // mono returns t's monotonic clock reading.
   236  // It returns 0 for a missing reading.
   237  // This function is used only for testing,
   238  // so it's OK that technically 0 is a valid
   239  // monotonic clock reading as well.
   240  func (t *Time) mono() int64 {
   241  	if t.wall&hasMonotonic == 0 {
   242  		return 0
   243  	}
   244  	return t.ext
   245  }
   246  
   247  // After reports whether the time instant t is after u.
   248  func (t Time) After(u Time) bool {
   249  	if t.wall&u.wall&hasMonotonic != 0 {
   250  		return t.ext > u.ext
   251  	}
   252  	ts := t.sec()
   253  	us := u.sec()
   254  	return ts > us || ts == us && t.nsec() > u.nsec()
   255  }
   256  
   257  // Before reports whether the time instant t is before u.
   258  func (t Time) Before(u Time) bool {
   259  	if t.wall&u.wall&hasMonotonic != 0 {
   260  		return t.ext < u.ext
   261  	}
   262  	ts := t.sec()
   263  	us := u.sec()
   264  	return ts < us || ts == us && t.nsec() < u.nsec()
   265  }
   266  
   267  // Equal reports whether t and u represent the same time instant.
   268  // Two times can be equal even if they are in different locations.
   269  // For example, 6:00 +0200 and 4:00 UTC are Equal.
   270  // See the documentation on the Time type for the pitfalls of using == with
   271  // Time values; most code should use Equal instead.
   272  func (t Time) Equal(u Time) bool {
   273  	if t.wall&u.wall&hasMonotonic != 0 {
   274  		return t.ext == u.ext
   275  	}
   276  	return t.sec() == u.sec() && t.nsec() == u.nsec()
   277  }
   278  
   279  // A Month specifies a month of the year (January = 1, ...).
   280  type Month int
   281  
   282  const (
   283  	January Month = 1 + iota
   284  	February
   285  	March
   286  	April
   287  	May
   288  	June
   289  	July
   290  	August
   291  	September
   292  	October
   293  	November
   294  	December
   295  )
   296  
   297  // String returns the English name of the month ("January", "February", ...).
   298  func (m Month) String() string {
   299  	if January <= m && m <= December {
   300  		return longMonthNames[m-1]
   301  	}
   302  	buf := make([]byte, 20)
   303  	n := fmtInt(buf, uint64(m))
   304  	return "%!Month(" + string(buf[n:]) + ")"
   305  }
   306  
   307  // A Weekday specifies a day of the week (Sunday = 0, ...).
   308  type Weekday int
   309  
   310  const (
   311  	Sunday Weekday = iota
   312  	Monday
   313  	Tuesday
   314  	Wednesday
   315  	Thursday
   316  	Friday
   317  	Saturday
   318  )
   319  
   320  // String returns the English name of the day ("Sunday", "Monday", ...).
   321  func (d Weekday) String() string {
   322  	if Sunday <= d && d <= Saturday {
   323  		return longDayNames[d]
   324  	}
   325  	buf := make([]byte, 20)
   326  	n := fmtInt(buf, uint64(d))
   327  	return "%!Weekday(" + string(buf[n:]) + ")"
   328  }
   329  
   330  // Computations on time.
   331  //
   332  // The zero value for a Time is defined to be
   333  //	January 1, year 1, 00:00:00.000000000 UTC
   334  // which (1) looks like a zero, or as close as you can get in a date
   335  // (1-1-1 00:00:00 UTC), (2) is unlikely enough to arise in practice to
   336  // be a suitable "not set" sentinel, unlike Jan 1 1970, and (3) has a
   337  // non-negative year even in time zones west of UTC, unlike 1-1-0
   338  // 00:00:00 UTC, which would be 12-31-(-1) 19:00:00 in New York.
   339  //
   340  // The zero Time value does not force a specific epoch for the time
   341  // representation. For example, to use the Unix epoch internally, we
   342  // could define that to distinguish a zero value from Jan 1 1970, that
   343  // time would be represented by sec=-1, nsec=1e9. However, it does
   344  // suggest a representation, namely using 1-1-1 00:00:00 UTC as the
   345  // epoch, and that's what we do.
   346  //
   347  // The Add and Sub computations are oblivious to the choice of epoch.
   348  //
   349  // The presentation computations - year, month, minute, and so on - all
   350  // rely heavily on division and modulus by positive constants. For
   351  // calendrical calculations we want these divisions to round down, even
   352  // for negative values, so that the remainder is always positive, but
   353  // Go's division (like most hardware division instructions) rounds to
   354  // zero. We can still do those computations and then adjust the result
   355  // for a negative numerator, but it's annoying to write the adjustment
   356  // over and over. Instead, we can change to a different epoch so long
   357  // ago that all the times we care about will be positive, and then round
   358  // to zero and round down coincide. These presentation routines already
   359  // have to add the zone offset, so adding the translation to the
   360  // alternate epoch is cheap. For example, having a non-negative time t
   361  // means that we can write
   362  //
   363  //	sec = t % 60
   364  //
   365  // instead of
   366  //
   367  //	sec = t % 60
   368  //	if sec < 0 {
   369  //		sec += 60
   370  //	}
   371  //
   372  // everywhere.
   373  //
   374  // The calendar runs on an exact 400 year cycle: a 400-year calendar
   375  // printed for 1970-2369 will apply as well to 2370-2769. Even the days
   376  // of the week match up. It simplifies the computations to choose the
   377  // cycle boundaries so that the exceptional years are always delayed as
   378  // long as possible. That means choosing a year equal to 1 mod 400, so
   379  // that the first leap year is the 4th year, the first missed leap year
   380  // is the 100th year, and the missed missed leap year is the 400th year.
   381  // So we'd prefer instead to print a calendar for 2001-2400 and reuse it
   382  // for 2401-2800.
   383  //
   384  // Finally, it's convenient if the delta between the Unix epoch and
   385  // long-ago epoch is representable by an int64 constant.
   386  //
   387  // These three considerations—choose an epoch as early as possible, that
   388  // uses a year equal to 1 mod 400, and that is no more than 2⁶³ seconds
   389  // earlier than 1970—bring us to the year -292277022399. We refer to
   390  // this year as the absolute zero year, and to times measured as a uint64
   391  // seconds since this year as absolute times.
   392  //
   393  // Times measured as an int64 seconds since the year 1—the representation
   394  // used for Time's sec field—are called internal times.
   395  //
   396  // Times measured as an int64 seconds since the year 1970 are called Unix
   397  // times.
   398  //
   399  // It is tempting to just use the year 1 as the absolute epoch, defining
   400  // that the routines are only valid for years >= 1. However, the
   401  // routines would then be invalid when displaying the epoch in time zones
   402  // west of UTC, since it is year 0. It doesn't seem tenable to say that
   403  // printing the zero time correctly isn't supported in half the time
   404  // zones. By comparison, it's reasonable to mishandle some times in
   405  // the year -292277022399.
   406  //
   407  // All this is opaque to clients of the API and can be changed if a
   408  // better implementation presents itself.
   409  
   410  const (
   411  	// The unsigned zero year for internal calculations.
   412  	// Must be 1 mod 400, and times before it will not compute correctly,
   413  	// but otherwise can be changed at will.
   414  	absoluteZeroYear = -292277022399
   415  
   416  	// The year of the zero Time.
   417  	// Assumed by the unixToInternal computation below.
   418  	internalYear = 1
   419  
   420  	// Offsets to convert between internal and absolute or Unix times.
   421  	absoluteToInternal int64 = (absoluteZeroYear - internalYear) * 365.2425 * secondsPerDay
   422  	internalToAbsolute       = -absoluteToInternal
   423  
   424  	unixToInternal int64 = (1969*365 + 1969/4 - 1969/100 + 1969/400) * secondsPerDay
   425  	internalToUnix int64 = -unixToInternal
   426  
   427  	wallToInternal int64 = (1884*365 + 1884/4 - 1884/100 + 1884/400) * secondsPerDay
   428  	internalToWall int64 = -wallToInternal
   429  )
   430  
   431  // IsZero reports whether t represents the zero time instant,
   432  // January 1, year 1, 00:00:00 UTC.
   433  func (t Time) IsZero() bool {
   434  	return t.sec() == 0 && t.nsec() == 0
   435  }
   436  
   437  // abs returns the time t as an absolute time, adjusted by the zone offset.
   438  // It is called when computing a presentation property like Month or Hour.
   439  func (t Time) abs() uint64 {
   440  	l := t.loc
   441  	// Avoid function calls when possible.
   442  	if l == nil || l == &localLoc {
   443  		l = l.get()
   444  	}
   445  	sec := t.unixSec()
   446  	if l != &utcLoc {
   447  		if l.cacheZone != nil && l.cacheStart <= sec && sec < l.cacheEnd {
   448  			sec += int64(l.cacheZone.offset)
   449  		} else {
   450  			_, offset, _, _, _ := l.lookup(sec)
   451  			sec += int64(offset)
   452  		}
   453  	}
   454  	return uint64(sec + (unixToInternal + internalToAbsolute))
   455  }
   456  
   457  // locabs is a combination of the Zone and abs methods,
   458  // extracting both return values from a single zone lookup.
   459  func (t Time) locabs() (name string, offset int, abs uint64) {
   460  	l := t.loc
   461  	if l == nil || l == &localLoc {
   462  		l = l.get()
   463  	}
   464  	// Avoid function call if we hit the local time cache.
   465  	sec := t.unixSec()
   466  	if l != &utcLoc {
   467  		if l.cacheZone != nil && l.cacheStart <= sec && sec < l.cacheEnd {
   468  			name = l.cacheZone.name
   469  			offset = l.cacheZone.offset
   470  		} else {
   471  			name, offset, _, _, _ = l.lookup(sec)
   472  		}
   473  		sec += int64(offset)
   474  	} else {
   475  		name = "UTC"
   476  	}
   477  	abs = uint64(sec + (unixToInternal + internalToAbsolute))
   478  	return
   479  }
   480  
   481  // Date returns the year, month, and day in which t occurs.
   482  func (t Time) Date() (year int, month Month, day int) {
   483  	year, month, day, _ = t.date(true)
   484  	return
   485  }
   486  
   487  // Year returns the year in which t occurs.
   488  func (t Time) Year() int {
   489  	year, _, _, _ := t.date(false)
   490  	return year
   491  }
   492  
   493  // Month returns the month of the year specified by t.
   494  func (t Time) Month() Month {
   495  	_, month, _, _ := t.date(true)
   496  	return month
   497  }
   498  
   499  // Day returns the day of the month specified by t.
   500  func (t Time) Day() int {
   501  	_, _, day, _ := t.date(true)
   502  	return day
   503  }
   504  
   505  // Weekday returns the day of the week specified by t.
   506  func (t Time) Weekday() Weekday {
   507  	return absWeekday(t.abs())
   508  }
   509  
   510  // absWeekday is like Weekday but operates on an absolute time.
   511  func absWeekday(abs uint64) Weekday {
   512  	// January 1 of the absolute year, like January 1 of 2001, was a Monday.
   513  	sec := (abs + uint64(Monday)*secondsPerDay) % secondsPerWeek
   514  	return Weekday(int(sec) / secondsPerDay)
   515  }
   516  
   517  // ISOWeek returns the ISO 8601 year and week number in which t occurs.
   518  // Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to
   519  // week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1
   520  // of year n+1.
   521  func (t Time) ISOWeek() (year, week int) {
   522  	// According to the rule that the first calendar week of a calendar year is
   523  	// the week including the first Thursday of that year, and that the last one is
   524  	// the week immediately preceding the first calendar week of the next calendar year.
   525  	// See https://www.iso.org/obp/ui#iso:std:iso:8601:-1:ed-1:v1:en:term:3.1.1.23 for details.
   526  
   527  	// weeks start with Monday
   528  	// Monday Tuesday Wednesday Thursday Friday Saturday Sunday
   529  	// 1      2       3         4        5      6        7
   530  	// +3     +2      +1        0        -1     -2       -3
   531  	// the offset to Thursday
   532  	abs := t.abs()
   533  	d := Thursday - absWeekday(abs)
   534  	// handle Sunday
   535  	if d == 4 {
   536  		d = -3
   537  	}
   538  	// find the Thursday of the calendar week
   539  	abs += uint64(d) * secondsPerDay
   540  	year, _, _, yday := absDate(abs, false)
   541  	return year, yday/7 + 1
   542  }
   543  
   544  // Clock returns the hour, minute, and second within the day specified by t.
   545  func (t Time) Clock() (hour, min, sec int) {
   546  	return absClock(t.abs())
   547  }
   548  
   549  // absClock is like clock but operates on an absolute time.
   550  func absClock(abs uint64) (hour, min, sec int) {
   551  	sec = int(abs % secondsPerDay)
   552  	hour = sec / secondsPerHour
   553  	sec -= hour * secondsPerHour
   554  	min = sec / secondsPerMinute
   555  	sec -= min * secondsPerMinute
   556  	return
   557  }
   558  
   559  // Hour returns the hour within the day specified by t, in the range [0, 23].
   560  func (t Time) Hour() int {
   561  	return int(t.abs()%secondsPerDay) / secondsPerHour
   562  }
   563  
   564  // Minute returns the minute offset within the hour specified by t, in the range [0, 59].
   565  func (t Time) Minute() int {
   566  	return int(t.abs()%secondsPerHour) / secondsPerMinute
   567  }
   568  
   569  // Second returns the second offset within the minute specified by t, in the range [0, 59].
   570  func (t Time) Second() int {
   571  	return int(t.abs() % secondsPerMinute)
   572  }
   573  
   574  // Nanosecond returns the nanosecond offset within the second specified by t,
   575  // in the range [0, 999999999].
   576  func (t Time) Nanosecond() int {
   577  	return int(t.nsec())
   578  }
   579  
   580  // YearDay returns the day of the year specified by t, in the range [1,365] for non-leap years,
   581  // and [1,366] in leap years.
   582  func (t Time) YearDay() int {
   583  	_, _, _, yday := t.date(false)
   584  	return yday + 1
   585  }
   586  
   587  // A Duration represents the elapsed time between two instants
   588  // as an int64 nanosecond count. The representation limits the
   589  // largest representable duration to approximately 290 years.
   590  type Duration int64
   591  
   592  const (
   593  	minDuration Duration = -1 << 63
   594  	maxDuration Duration = 1<<63 - 1
   595  )
   596  
   597  // Common durations. There is no definition for units of Day or larger
   598  // to avoid confusion across daylight savings time zone transitions.
   599  //
   600  // To count the number of units in a Duration, divide:
   601  //	second := time.Second
   602  //	fmt.Print(int64(second/time.Millisecond)) // prints 1000
   603  //
   604  // To convert an integer number of units to a Duration, multiply:
   605  //	seconds := 10
   606  //	fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
   607  //
   608  const (
   609  	Nanosecond  Duration = 1
   610  	Microsecond          = 1000 * Nanosecond
   611  	Millisecond          = 1000 * Microsecond
   612  	Second               = 1000 * Millisecond
   613  	Minute               = 60 * Second
   614  	Hour                 = 60 * Minute
   615  )
   616  
   617  // String returns a string representing the duration in the form "72h3m0.5s".
   618  // Leading zero units are omitted. As a special case, durations less than one
   619  // second format use a smaller unit (milli-, micro-, or nanoseconds) to ensure
   620  // that the leading digit is non-zero. The zero duration formats as 0s.
   621  func (d Duration) String() string {
   622  	// Largest time is 2540400h10m10.000000000s
   623  	var buf [32]byte
   624  	w := len(buf)
   625  
   626  	u := uint64(d)
   627  	neg := d < 0
   628  	if neg {
   629  		u = -u
   630  	}
   631  
   632  	if u < uint64(Second) {
   633  		// Special case: if duration is smaller than a second,
   634  		// use smaller units, like 1.2ms
   635  		var prec int
   636  		w--
   637  		buf[w] = 's'
   638  		w--
   639  		switch {
   640  		case u == 0:
   641  			return "0s"
   642  		case u < uint64(Microsecond):
   643  			// print nanoseconds
   644  			prec = 0
   645  			buf[w] = 'n'
   646  		case u < uint64(Millisecond):
   647  			// print microseconds
   648  			prec = 3
   649  			// U+00B5 'µ' micro sign == 0xC2 0xB5
   650  			w-- // Need room for two bytes.
   651  			copy(buf[w:], "µ")
   652  		default:
   653  			// print milliseconds
   654  			prec = 6
   655  			buf[w] = 'm'
   656  		}
   657  		w, u = fmtFrac(buf[:w], u, prec)
   658  		w = fmtInt(buf[:w], u)
   659  	} else {
   660  		w--
   661  		buf[w] = 's'
   662  
   663  		w, u = fmtFrac(buf[:w], u, 9)
   664  
   665  		// u is now integer seconds
   666  		w = fmtInt(buf[:w], u%60)
   667  		u /= 60
   668  
   669  		// u is now integer minutes
   670  		if u > 0 {
   671  			w--
   672  			buf[w] = 'm'
   673  			w = fmtInt(buf[:w], u%60)
   674  			u /= 60
   675  
   676  			// u is now integer hours
   677  			// Stop at hours because days can be different lengths.
   678  			if u > 0 {
   679  				w--
   680  				buf[w] = 'h'
   681  				w = fmtInt(buf[:w], u)
   682  			}
   683  		}
   684  	}
   685  
   686  	if neg {
   687  		w--
   688  		buf[w] = '-'
   689  	}
   690  
   691  	return string(buf[w:])
   692  }
   693  
   694  // fmtFrac formats the fraction of v/10**prec (e.g., ".12345") into the
   695  // tail of buf, omitting trailing zeros. It omits the decimal
   696  // point too when the fraction is 0. It returns the index where the
   697  // output bytes begin and the value v/10**prec.
   698  func fmtFrac(buf []byte, v uint64, prec int) (nw int, nv uint64) {
   699  	// Omit trailing zeros up to and including decimal point.
   700  	w := len(buf)
   701  	print := false
   702  	for i := 0; i < prec; i++ {
   703  		digit := v % 10
   704  		print = print || digit != 0
   705  		if print {
   706  			w--
   707  			buf[w] = byte(digit) + '0'
   708  		}
   709  		v /= 10
   710  	}
   711  	if print {
   712  		w--
   713  		buf[w] = '.'
   714  	}
   715  	return w, v
   716  }
   717  
   718  // fmtInt formats v into the tail of buf.
   719  // It returns the index where the output begins.
   720  func fmtInt(buf []byte, v uint64) int {
   721  	w := len(buf)
   722  	if v == 0 {
   723  		w--
   724  		buf[w] = '0'
   725  	} else {
   726  		for v > 0 {
   727  			w--
   728  			buf[w] = byte(v%10) + '0'
   729  			v /= 10
   730  		}
   731  	}
   732  	return w
   733  }
   734  
   735  // Nanoseconds returns the duration as an integer nanosecond count.
   736  func (d Duration) Nanoseconds() int64 { return int64(d) }
   737  
   738  // Microseconds returns the duration as an integer microsecond count.
   739  func (d Duration) Microseconds() int64 { return int64(d) / 1e3 }
   740  
   741  // Milliseconds returns the duration as an integer millisecond count.
   742  func (d Duration) Milliseconds() int64 { return int64(d) / 1e6 }
   743  
   744  // These methods return float64 because the dominant
   745  // use case is for printing a floating point number like 1.5s, and
   746  // a truncation to integer would make them not useful in those cases.
   747  // Splitting the integer and fraction ourselves guarantees that
   748  // converting the returned float64 to an integer rounds the same
   749  // way that a pure integer conversion would have, even in cases
   750  // where, say, float64(d.Nanoseconds())/1e9 would have rounded
   751  // differently.
   752  
   753  // Seconds returns the duration as a floating point number of seconds.
   754  func (d Duration) Seconds() float64 {
   755  	sec := d / Second
   756  	nsec := d % Second
   757  	return float64(sec) + float64(nsec)/1e9
   758  }
   759  
   760  // Minutes returns the duration as a floating point number of minutes.
   761  func (d Duration) Minutes() float64 {
   762  	min := d / Minute
   763  	nsec := d % Minute
   764  	return float64(min) + float64(nsec)/(60*1e9)
   765  }
   766  
   767  // Hours returns the duration as a floating point number of hours.
   768  func (d Duration) Hours() float64 {
   769  	hour := d / Hour
   770  	nsec := d % Hour
   771  	return float64(hour) + float64(nsec)/(60*60*1e9)
   772  }
   773  
   774  // Truncate returns the result of rounding d toward zero to a multiple of m.
   775  // If m <= 0, Truncate returns d unchanged.
   776  func (d Duration) Truncate(m Duration) Duration {
   777  	if m <= 0 {
   778  		return d
   779  	}
   780  	return d - d%m
   781  }
   782  
   783  // lessThanHalf reports whether x+x < y but avoids overflow,
   784  // assuming x and y are both positive (Duration is signed).
   785  func lessThanHalf(x, y Duration) bool {
   786  	return uint64(x)+uint64(x) < uint64(y)
   787  }
   788  
   789  // Round returns the result of rounding d to the nearest multiple of m.
   790  // The rounding behavior for halfway values is to round away from zero.
   791  // If the result exceeds the maximum (or minimum)
   792  // value that can be stored in a Duration,
   793  // Round returns the maximum (or minimum) duration.
   794  // If m <= 0, Round returns d unchanged.
   795  func (d Duration) Round(m Duration) Duration {
   796  	if m <= 0 {
   797  		return d
   798  	}
   799  	r := d % m
   800  	if d < 0 {
   801  		r = -r
   802  		if lessThanHalf(r, m) {
   803  			return d + r
   804  		}
   805  		if d1 := d - m + r; d1 < d {
   806  			return d1
   807  		}
   808  		return minDuration // overflow
   809  	}
   810  	if lessThanHalf(r, m) {
   811  		return d - r
   812  	}
   813  	if d1 := d + m - r; d1 > d {
   814  		return d1
   815  	}
   816  	return maxDuration // overflow
   817  }
   818  
   819  // Add returns the time t+d.
   820  func (t Time) Add(d Duration) Time {
   821  	dsec := int64(d / 1e9)
   822  	nsec := t.nsec() + int32(d%1e9)
   823  	if nsec >= 1e9 {
   824  		dsec++
   825  		nsec -= 1e9
   826  	} else if nsec < 0 {
   827  		dsec--
   828  		nsec += 1e9
   829  	}
   830  	t.wall = t.wall&^nsecMask | uint64(nsec) // update nsec
   831  	t.addSec(dsec)
   832  	if t.wall&hasMonotonic != 0 {
   833  		te := t.ext + int64(d)
   834  		if d < 0 && te > t.ext || d > 0 && te < t.ext {
   835  			// Monotonic clock reading now out of range; degrade to wall-only.
   836  			t.stripMono()
   837  		} else {
   838  			t.ext = te
   839  		}
   840  	}
   841  	return t
   842  }
   843  
   844  // Sub returns the duration t-u. If the result exceeds the maximum (or minimum)
   845  // value that can be stored in a Duration, the maximum (or minimum) duration
   846  // will be returned.
   847  // To compute t-d for a duration d, use t.Add(-d).
   848  func (t Time) Sub(u Time) Duration {
   849  	if t.wall&u.wall&hasMonotonic != 0 {
   850  		te := t.ext
   851  		ue := u.ext
   852  		d := Duration(te - ue)
   853  		if d < 0 && te > ue {
   854  			return maxDuration // t - u is positive out of range
   855  		}
   856  		if d > 0 && te < ue {
   857  			return minDuration // t - u is negative out of range
   858  		}
   859  		return d
   860  	}
   861  	d := Duration(t.sec()-u.sec())*Second + Duration(t.nsec()-u.nsec())
   862  	// Check for overflow or underflow.
   863  	switch {
   864  	case u.Add(d).Equal(t):
   865  		return d // d is correct
   866  	case t.Before(u):
   867  		return minDuration // t - u is negative out of range
   868  	default:
   869  		return maxDuration // t - u is positive out of range
   870  	}
   871  }
   872  
   873  // Since returns the time elapsed since t.
   874  // It is shorthand for time.Now().Sub(t).
   875  func Since(t Time) Duration {
   876  	var now Time
   877  	if t.wall&hasMonotonic != 0 {
   878  		// Common case optimization: if t has monotonic time, then Sub will use only it.
   879  		now = Time{hasMonotonic, runtimeNano() - startNano, nil}
   880  	} else {
   881  		now = Now()
   882  	}
   883  	return now.Sub(t)
   884  }
   885  
   886  // Until returns the duration until t.
   887  // It is shorthand for t.Sub(time.Now()).
   888  func Until(t Time) Duration {
   889  	var now Time
   890  	if t.wall&hasMonotonic != 0 {
   891  		// Common case optimization: if t has monotonic time, then Sub will use only it.
   892  		now = Time{hasMonotonic, runtimeNano() - startNano, nil}
   893  	} else {
   894  		now = Now()
   895  	}
   896  	return t.Sub(now)
   897  }
   898  
   899  // AddDate returns the time corresponding to adding the
   900  // given number of years, months, and days to t.
   901  // For example, AddDate(-1, 2, 3) applied to January 1, 2011
   902  // returns March 4, 2010.
   903  //
   904  // AddDate normalizes its result in the same way that Date does,
   905  // so, for example, adding one month to October 31 yields
   906  // December 1, the normalized form for November 31.
   907  func (t Time) AddDate(years int, months int, days int) Time {
   908  	year, month, day := t.Date()
   909  	hour, min, sec := t.Clock()
   910  	return Date(year+years, month+Month(months), day+days, hour, min, sec, int(t.nsec()), t.Location())
   911  }
   912  
   913  const (
   914  	secondsPerMinute = 60
   915  	secondsPerHour   = 60 * secondsPerMinute
   916  	secondsPerDay    = 24 * secondsPerHour
   917  	secondsPerWeek   = 7 * secondsPerDay
   918  	daysPer400Years  = 365*400 + 97
   919  	daysPer100Years  = 365*100 + 24
   920  	daysPer4Years    = 365*4 + 1
   921  )
   922  
   923  // date computes the year, day of year, and when full=true,
   924  // the month and day in which t occurs.
   925  func (t Time) date(full bool) (year int, month Month, day int, yday int) {
   926  	return absDate(t.abs(), full)
   927  }
   928  
   929  // absDate is like date but operates on an absolute time.
   930  func absDate(abs uint64, full bool) (year int, month Month, day int, yday int) {
   931  	// Split into time and day.
   932  	d := abs / secondsPerDay
   933  
   934  	// Account for 400 year cycles.
   935  	n := d / daysPer400Years
   936  	y := 400 * n
   937  	d -= daysPer400Years * n
   938  
   939  	// Cut off 100-year cycles.
   940  	// The last cycle has one extra leap year, so on the last day
   941  	// of that year, day / daysPer100Years will be 4 instead of 3.
   942  	// Cut it back down to 3 by subtracting n>>2.
   943  	n = d / daysPer100Years
   944  	n -= n >> 2
   945  	y += 100 * n
   946  	d -= daysPer100Years * n
   947  
   948  	// Cut off 4-year cycles.
   949  	// The last cycle has a missing leap year, which does not
   950  	// affect the computation.
   951  	n = d / daysPer4Years
   952  	y += 4 * n
   953  	d -= daysPer4Years * n
   954  
   955  	// Cut off years within a 4-year cycle.
   956  	// The last year is a leap year, so on the last day of that year,
   957  	// day / 365 will be 4 instead of 3. Cut it back down to 3
   958  	// by subtracting n>>2.
   959  	n = d / 365
   960  	n -= n >> 2
   961  	y += n
   962  	d -= 365 * n
   963  
   964  	year = int(int64(y) + absoluteZeroYear)
   965  	yday = int(d)
   966  
   967  	if !full {
   968  		return
   969  	}
   970  
   971  	day = yday
   972  	if isLeap(year) {
   973  		// Leap year
   974  		switch {
   975  		case day > 31+29-1:
   976  			// After leap day; pretend it wasn't there.
   977  			day--
   978  		case day == 31+29-1:
   979  			// Leap day.
   980  			month = February
   981  			day = 29
   982  			return
   983  		}
   984  	}
   985  
   986  	// Estimate month on assumption that every month has 31 days.
   987  	// The estimate may be too low by at most one month, so adjust.
   988  	month = Month(day / 31)
   989  	end := int(daysBefore[month+1])
   990  	var begin int
   991  	if day >= end {
   992  		month++
   993  		begin = end
   994  	} else {
   995  		begin = int(daysBefore[month])
   996  	}
   997  
   998  	month++ // because January is 1
   999  	day = day - begin + 1
  1000  	return
  1001  }
  1002  
  1003  // daysBefore[m] counts the number of days in a non-leap year
  1004  // before month m begins. There is an entry for m=12, counting
  1005  // the number of days before January of next year (365).
  1006  var daysBefore = [...]int32{
  1007  	0,
  1008  	31,
  1009  	31 + 28,
  1010  	31 + 28 + 31,
  1011  	31 + 28 + 31 + 30,
  1012  	31 + 28 + 31 + 30 + 31,
  1013  	31 + 28 + 31 + 30 + 31 + 30,
  1014  	31 + 28 + 31 + 30 + 31 + 30 + 31,
  1015  	31 + 28 + 31 + 30 + 31 + 30 + 31 + 31,
  1016  	31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30,
  1017  	31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31,
  1018  	31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30,
  1019  	31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31,
  1020  }
  1021  
  1022  func daysIn(m Month, year int) int {
  1023  	if m == February && isLeap(year) {
  1024  		return 29
  1025  	}
  1026  	return int(daysBefore[m] - daysBefore[m-1])
  1027  }
  1028  
  1029  // daysSinceEpoch takes a year and returns the number of days from
  1030  // the absolute epoch to the start of that year.
  1031  // This is basically (year - zeroYear) * 365, but accounting for leap days.
  1032  func daysSinceEpoch(year int) uint64 {
  1033  	y := uint64(int64(year) - absoluteZeroYear)
  1034  
  1035  	// Add in days from 400-year cycles.
  1036  	n := y / 400
  1037  	y -= 400 * n
  1038  	d := daysPer400Years * n
  1039  
  1040  	// Add in 100-year cycles.
  1041  	n = y / 100
  1042  	y -= 100 * n
  1043  	d += daysPer100Years * n
  1044  
  1045  	// Add in 4-year cycles.
  1046  	n = y / 4
  1047  	y -= 4 * n
  1048  	d += daysPer4Years * n
  1049  
  1050  	// Add in non-leap years.
  1051  	n = y
  1052  	d += 365 * n
  1053  
  1054  	return d
  1055  }
  1056  
  1057  // Provided by package runtime.
  1058  func now() (sec int64, nsec int32, mono int64)
  1059  
  1060  // runtimeNano returns the current value of the runtime clock in nanoseconds.
  1061  //go:linkname runtimeNano runtime.nanotime
  1062  func runtimeNano() int64
  1063  
  1064  // Monotonic times are reported as offsets from startNano.
  1065  // We initialize startNano to runtimeNano() - 1 so that on systems where
  1066  // monotonic time resolution is fairly low (e.g. Windows 2008
  1067  // which appears to have a default resolution of 15ms),
  1068  // we avoid ever reporting a monotonic time of 0.
  1069  // (Callers may want to use 0 as "time not set".)
  1070  var startNano int64 = runtimeNano() - 1
  1071  
  1072  // Now returns the current local time.
  1073  func Now() Time {
  1074  	sec, nsec, mono := now()
  1075  	mono -= startNano
  1076  	sec += unixToInternal - minWall
  1077  	if uint64(sec)>>33 != 0 {
  1078  		return Time{uint64(nsec), sec + minWall, Local}
  1079  	}
  1080  	return Time{hasMonotonic | uint64(sec)<<nsecShift | uint64(nsec), mono, Local}
  1081  }
  1082  
  1083  func unixTime(sec int64, nsec int32) Time {
  1084  	return Time{uint64(nsec), sec + unixToInternal, Local}
  1085  }
  1086  
  1087  // UTC returns t with the location set to UTC.
  1088  func (t Time) UTC() Time {
  1089  	t.setLoc(&utcLoc)
  1090  	return t
  1091  }
  1092  
  1093  // Local returns t with the location set to local time.
  1094  func (t Time) Local() Time {
  1095  	t.setLoc(Local)
  1096  	return t
  1097  }
  1098  
  1099  // In returns a copy of t representing the same time instant, but
  1100  // with the copy's location information set to loc for display
  1101  // purposes.
  1102  //
  1103  // In panics if loc is nil.
  1104  func (t Time) In(loc *Location) Time {
  1105  	if loc == nil {
  1106  		panic("time: missing Location in call to Time.In")
  1107  	}
  1108  	t.setLoc(loc)
  1109  	return t
  1110  }
  1111  
  1112  // Location returns the time zone information associated with t.
  1113  func (t Time) Location() *Location {
  1114  	l := t.loc
  1115  	if l == nil {
  1116  		l = UTC
  1117  	}
  1118  	return l
  1119  }
  1120  
  1121  // Zone computes the time zone in effect at time t, returning the abbreviated
  1122  // name of the zone (such as "CET") and its offset in seconds east of UTC.
  1123  func (t Time) Zone() (name string, offset int) {
  1124  	name, offset, _, _, _ = t.loc.lookup(t.unixSec())
  1125  	return
  1126  }
  1127  
  1128  // Unix returns t as a Unix time, the number of seconds elapsed
  1129  // since January 1, 1970 UTC. The result does not depend on the
  1130  // location associated with t.
  1131  // Unix-like operating systems often record time as a 32-bit
  1132  // count of seconds, but since the method here returns a 64-bit
  1133  // value it is valid for billions of years into the past or future.
  1134  func (t Time) Unix() int64 {
  1135  	return t.unixSec()
  1136  }
  1137  
  1138  // UnixMilli returns t as a Unix time, the number of milliseconds elapsed since
  1139  // January 1, 1970 UTC. The result is undefined if the Unix time in
  1140  // milliseconds cannot be represented by an int64 (a date more than 292 million
  1141  // years before or after 1970). The result does not depend on the
  1142  // location associated with t.
  1143  func (t Time) UnixMilli() int64 {
  1144  	return t.unixSec()*1e3 + int64(t.nsec())/1e6
  1145  }
  1146  
  1147  // UnixMicro returns t as a Unix time, the number of microseconds elapsed since
  1148  // January 1, 1970 UTC. The result is undefined if the Unix time in
  1149  // microseconds cannot be represented by an int64 (a date before year -290307 or
  1150  // after year 294246). The result does not depend on the location associated
  1151  // with t.
  1152  func (t Time) UnixMicro() int64 {
  1153  	return t.unixSec()*1e6 + int64(t.nsec())/1e3
  1154  }
  1155  
  1156  // UnixNano returns t as a Unix time, the number of nanoseconds elapsed
  1157  // since January 1, 1970 UTC. The result is undefined if the Unix time
  1158  // in nanoseconds cannot be represented by an int64 (a date before the year
  1159  // 1678 or after 2262). Note that this means the result of calling UnixNano
  1160  // on the zero Time is undefined. The result does not depend on the
  1161  // location associated with t.
  1162  func (t Time) UnixNano() int64 {
  1163  	return (t.unixSec())*1e9 + int64(t.nsec())
  1164  }
  1165  
  1166  const timeBinaryVersion byte = 1
  1167  
  1168  // MarshalBinary implements the encoding.BinaryMarshaler interface.
  1169  func (t Time) MarshalBinary() ([]byte, error) {
  1170  	var offsetMin int16 // minutes east of UTC. -1 is UTC.
  1171  
  1172  	if t.Location() == UTC {
  1173  		offsetMin = -1
  1174  	} else {
  1175  		_, offset := t.Zone()
  1176  		if offset%60 != 0 {
  1177  			return nil, errors.New("Time.MarshalBinary: zone offset has fractional minute")
  1178  		}
  1179  		offset /= 60
  1180  		if offset < -32768 || offset == -1 || offset > 32767 {
  1181  			return nil, errors.New("Time.MarshalBinary: unexpected zone offset")
  1182  		}
  1183  		offsetMin = int16(offset)
  1184  	}
  1185  
  1186  	sec := t.sec()
  1187  	nsec := t.nsec()
  1188  	enc := []byte{
  1189  		timeBinaryVersion, // byte 0 : version
  1190  		byte(sec >> 56),   // bytes 1-8: seconds
  1191  		byte(sec >> 48),
  1192  		byte(sec >> 40),
  1193  		byte(sec >> 32),
  1194  		byte(sec >> 24),
  1195  		byte(sec >> 16),
  1196  		byte(sec >> 8),
  1197  		byte(sec),
  1198  		byte(nsec >> 24), // bytes 9-12: nanoseconds
  1199  		byte(nsec >> 16),
  1200  		byte(nsec >> 8),
  1201  		byte(nsec),
  1202  		byte(offsetMin >> 8), // bytes 13-14: zone offset in minutes
  1203  		byte(offsetMin),
  1204  	}
  1205  
  1206  	return enc, nil
  1207  }
  1208  
  1209  // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
  1210  func (t *Time) UnmarshalBinary(data []byte) error {
  1211  	buf := data
  1212  	if len(buf) == 0 {
  1213  		return errors.New("Time.UnmarshalBinary: no data")
  1214  	}
  1215  
  1216  	if buf[0] != timeBinaryVersion {
  1217  		return errors.New("Time.UnmarshalBinary: unsupported version")
  1218  	}
  1219  
  1220  	if len(buf) != /*version*/ 1+ /*sec*/ 8+ /*nsec*/ 4+ /*zone offset*/ 2 {
  1221  		return errors.New("Time.UnmarshalBinary: invalid length")
  1222  	}
  1223  
  1224  	buf = buf[1:]
  1225  	sec := int64(buf[7]) | int64(buf[6])<<8 | int64(buf[5])<<16 | int64(buf[4])<<24 |
  1226  		int64(buf[3])<<32 | int64(buf[2])<<40 | int64(buf[1])<<48 | int64(buf[0])<<56
  1227  
  1228  	buf = buf[8:]
  1229  	nsec := int32(buf[3]) | int32(buf[2])<<8 | int32(buf[1])<<16 | int32(buf[0])<<24
  1230  
  1231  	buf = buf[4:]
  1232  	offset := int(int16(buf[1])|int16(buf[0])<<8) * 60
  1233  
  1234  	*t = Time{}
  1235  	t.wall = uint64(nsec)
  1236  	t.ext = sec
  1237  
  1238  	if offset == -1*60 {
  1239  		t.setLoc(&utcLoc)
  1240  	} else if _, localoff, _, _, _ := Local.lookup(t.unixSec()); offset == localoff {
  1241  		t.setLoc(Local)
  1242  	} else {
  1243  		t.setLoc(FixedZone("", offset))
  1244  	}
  1245  
  1246  	return nil
  1247  }
  1248  
  1249  // TODO(rsc): Remove GobEncoder, GobDecoder, MarshalJSON, UnmarshalJSON in Go 2.
  1250  // The same semantics will be provided by the generic MarshalBinary, MarshalText,
  1251  // UnmarshalBinary, UnmarshalText.
  1252  
  1253  // GobEncode implements the gob.GobEncoder interface.
  1254  func (t Time) GobEncode() ([]byte, error) {
  1255  	return t.MarshalBinary()
  1256  }
  1257  
  1258  // GobDecode implements the gob.GobDecoder interface.
  1259  func (t *Time) GobDecode(data []byte) error {
  1260  	return t.UnmarshalBinary(data)
  1261  }
  1262  
  1263  // MarshalJSON implements the json.Marshaler interface.
  1264  // The time is a quoted string in RFC 3339 format, with sub-second precision added if present.
  1265  func (t Time) MarshalJSON() ([]byte, error) {
  1266  	if y := t.Year(); y < 0 || y >= 10000 {
  1267  		// RFC 3339 is clear that years are 4 digits exactly.
  1268  		// See golang.org/issue/4556#c15 for more discussion.
  1269  		return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]")
  1270  	}
  1271  
  1272  	b := make([]byte, 0, len(RFC3339Nano)+2)
  1273  	b = append(b, '"')
  1274  	b = t.AppendFormat(b, RFC3339Nano)
  1275  	b = append(b, '"')
  1276  	return b, nil
  1277  }
  1278  
  1279  // UnmarshalJSON implements the json.Unmarshaler interface.
  1280  // The time is expected to be a quoted string in RFC 3339 format.
  1281  func (t *Time) UnmarshalJSON(data []byte) error {
  1282  	// Ignore null, like in the main JSON package.
  1283  	if string(data) == "null" {
  1284  		return nil
  1285  	}
  1286  	// Fractional seconds are handled implicitly by Parse.
  1287  	var err error
  1288  	*t, err = Parse(`"`+RFC3339+`"`, string(data))
  1289  	return err
  1290  }
  1291  
  1292  // MarshalText implements the encoding.TextMarshaler interface.
  1293  // The time is formatted in RFC 3339 format, with sub-second precision added if present.
  1294  func (t Time) MarshalText() ([]byte, error) {
  1295  	if y := t.Year(); y < 0 || y >= 10000 {
  1296  		return nil, errors.New("Time.MarshalText: year outside of range [0,9999]")
  1297  	}
  1298  
  1299  	b := make([]byte, 0, len(RFC3339Nano))
  1300  	return t.AppendFormat(b, RFC3339Nano), nil
  1301  }
  1302  
  1303  // UnmarshalText implements the encoding.TextUnmarshaler interface.
  1304  // The time is expected to be in RFC 3339 format.
  1305  func (t *Time) UnmarshalText(data []byte) error {
  1306  	// Fractional seconds are handled implicitly by Parse.
  1307  	var err error
  1308  	*t, err = Parse(RFC3339, string(data))
  1309  	return err
  1310  }
  1311  
  1312  // Unix returns the local Time corresponding to the given Unix time,
  1313  // sec seconds and nsec nanoseconds since January 1, 1970 UTC.
  1314  // It is valid to pass nsec outside the range [0, 999999999].
  1315  // Not all sec values have a corresponding time value. One such
  1316  // value is 1<<63-1 (the largest int64 value).
  1317  func Unix(sec int64, nsec int64) Time {
  1318  	if nsec < 0 || nsec >= 1e9 {
  1319  		n := nsec / 1e9
  1320  		sec += n
  1321  		nsec -= n * 1e9
  1322  		if nsec < 0 {
  1323  			nsec += 1e9
  1324  			sec--
  1325  		}
  1326  	}
  1327  	return unixTime(sec, int32(nsec))
  1328  }
  1329  
  1330  // UnixMilli returns the local Time corresponding to the given Unix time,
  1331  // msec milliseconds since January 1, 1970 UTC.
  1332  func UnixMilli(msec int64) Time {
  1333  	return Unix(msec/1e3, (msec%1e3)*1e6)
  1334  }
  1335  
  1336  // UnixMicro returns the local Time corresponding to the given Unix time,
  1337  // usec microseconds since January 1, 1970 UTC.
  1338  func UnixMicro(usec int64) Time {
  1339  	return Unix(usec/1e6, (usec%1e6)*1e3)
  1340  }
  1341  
  1342  // IsDST reports whether the time in the configured location is in Daylight Savings Time.
  1343  func (t Time) IsDST() bool {
  1344  	_, _, _, _, isDST := t.loc.lookup(t.Unix())
  1345  	return isDST
  1346  }
  1347  
  1348  func isLeap(year int) bool {
  1349  	return year%4 == 0 && (year%100 != 0 || year%400 == 0)
  1350  }
  1351  
  1352  // norm returns nhi, nlo such that
  1353  //	hi * base + lo == nhi * base + nlo
  1354  //	0 <= nlo < base
  1355  func norm(hi, lo, base int) (nhi, nlo int) {
  1356  	if lo < 0 {
  1357  		n := (-lo-1)/base + 1
  1358  		hi -= n
  1359  		lo += n * base
  1360  	}
  1361  	if lo >= base {
  1362  		n := lo / base
  1363  		hi += n
  1364  		lo -= n * base
  1365  	}
  1366  	return hi, lo
  1367  }
  1368  
  1369  // Date returns the Time corresponding to
  1370  //	yyyy-mm-dd hh:mm:ss + nsec nanoseconds
  1371  // in the appropriate zone for that time in the given location.
  1372  //
  1373  // The month, day, hour, min, sec, and nsec values may be outside
  1374  // their usual ranges and will be normalized during the conversion.
  1375  // For example, October 32 converts to November 1.
  1376  //
  1377  // A daylight savings time transition skips or repeats times.
  1378  // For example, in the United States, March 13, 2011 2:15am never occurred,
  1379  // while November 6, 2011 1:15am occurred twice. In such cases, the
  1380  // choice of time zone, and therefore the time, is not well-defined.
  1381  // Date returns a time that is correct in one of the two zones involved
  1382  // in the transition, but it does not guarantee which.
  1383  //
  1384  // Date panics if loc is nil.
  1385  func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time {
  1386  	if loc == nil {
  1387  		panic("time: missing Location in call to Date")
  1388  	}
  1389  
  1390  	// Normalize month, overflowing into year.
  1391  	m := int(month) - 1
  1392  	year, m = norm(year, m, 12)
  1393  	month = Month(m) + 1
  1394  
  1395  	// Normalize nsec, sec, min, hour, overflowing into day.
  1396  	sec, nsec = norm(sec, nsec, 1e9)
  1397  	min, sec = norm(min, sec, 60)
  1398  	hour, min = norm(hour, min, 60)
  1399  	day, hour = norm(day, hour, 24)
  1400  
  1401  	// Compute days since the absolute epoch.
  1402  	d := daysSinceEpoch(year)
  1403  
  1404  	// Add in days before this month.
  1405  	d += uint64(daysBefore[month-1])
  1406  	if isLeap(year) && month >= March {
  1407  		d++ // February 29
  1408  	}
  1409  
  1410  	// Add in days before today.
  1411  	d += uint64(day - 1)
  1412  
  1413  	// Add in time elapsed today.
  1414  	abs := d * secondsPerDay
  1415  	abs += uint64(hour*secondsPerHour + min*secondsPerMinute + sec)
  1416  
  1417  	unix := int64(abs) + (absoluteToInternal + internalToUnix)
  1418  
  1419  	// Look for zone offset for expected time, so we can adjust to UTC.
  1420  	// The lookup function expects UTC, so first we pass unix in the
  1421  	// hope that it will not be too close to a zone transition,
  1422  	// and then adjust if it is.
  1423  	_, offset, start, end, _ := loc.lookup(unix)
  1424  	if offset != 0 {
  1425  		utc := unix - int64(offset)
  1426  		// If utc is valid for the time zone we found, then we have the right offset.
  1427  		// If not, we get the correct offset by looking up utc in the location.
  1428  		if utc < start || utc >= end {
  1429  			_, offset, _, _, _ = loc.lookup(utc)
  1430  		}
  1431  		unix -= int64(offset)
  1432  	}
  1433  
  1434  	t := unixTime(unix, int32(nsec))
  1435  	t.setLoc(loc)
  1436  	return t
  1437  }
  1438  
  1439  // Truncate returns the result of rounding t down to a multiple of d (since the zero time).
  1440  // If d <= 0, Truncate returns t stripped of any monotonic clock reading but otherwise unchanged.
  1441  //
  1442  // Truncate operates on the time as an absolute duration since the
  1443  // zero time; it does not operate on the presentation form of the
  1444  // time. Thus, Truncate(Hour) may return a time with a non-zero
  1445  // minute, depending on the time's Location.
  1446  func (t Time) Truncate(d Duration) Time {
  1447  	t.stripMono()
  1448  	if d <= 0 {
  1449  		return t
  1450  	}
  1451  	_, r := div(t, d)
  1452  	return t.Add(-r)
  1453  }
  1454  
  1455  // Round returns the result of rounding t to the nearest multiple of d (since the zero time).
  1456  // The rounding behavior for halfway values is to round up.
  1457  // If d <= 0, Round returns t stripped of any monotonic clock reading but otherwise unchanged.
  1458  //
  1459  // Round operates on the time as an absolute duration since the
  1460  // zero time; it does not operate on the presentation form of the
  1461  // time. Thus, Round(Hour) may return a time with a non-zero
  1462  // minute, depending on the time's Location.
  1463  func (t Time) Round(d Duration) Time {
  1464  	t.stripMono()
  1465  	if d <= 0 {
  1466  		return t
  1467  	}
  1468  	_, r := div(t, d)
  1469  	if lessThanHalf(r, d) {
  1470  		return t.Add(-r)
  1471  	}
  1472  	return t.Add(d - r)
  1473  }
  1474  
  1475  // div divides t by d and returns the quotient parity and remainder.
  1476  // We don't use the quotient parity anymore (round half up instead of round to even)
  1477  // but it's still here in case we change our minds.
  1478  func div(t Time, d Duration) (qmod2 int, r Duration) {
  1479  	neg := false
  1480  	nsec := t.nsec()
  1481  	sec := t.sec()
  1482  	if sec < 0 {
  1483  		// Operate on absolute value.
  1484  		neg = true
  1485  		sec = -sec
  1486  		nsec = -nsec
  1487  		if nsec < 0 {
  1488  			nsec += 1e9
  1489  			sec-- // sec >= 1 before the -- so safe
  1490  		}
  1491  	}
  1492  
  1493  	switch {
  1494  	// Special case: 2d divides 1 second.
  1495  	case d < Second && Second%(d+d) == 0:
  1496  		qmod2 = int(nsec/int32(d)) & 1
  1497  		r = Duration(nsec % int32(d))
  1498  
  1499  	// Special case: d is a multiple of 1 second.
  1500  	case d%Second == 0:
  1501  		d1 := int64(d / Second)
  1502  		qmod2 = int(sec/d1) & 1
  1503  		r = Duration(sec%d1)*Second + Duration(nsec)
  1504  
  1505  	// General case.
  1506  	// This could be faster if more cleverness were applied,
  1507  	// but it's really only here to avoid special case restrictions in the API.
  1508  	// No one will care about these cases.
  1509  	default:
  1510  		// Compute nanoseconds as 128-bit number.
  1511  		sec := uint64(sec)
  1512  		tmp := (sec >> 32) * 1e9
  1513  		u1 := tmp >> 32
  1514  		u0 := tmp << 32
  1515  		tmp = (sec & 0xFFFFFFFF) * 1e9
  1516  		u0x, u0 := u0, u0+tmp
  1517  		if u0 < u0x {
  1518  			u1++
  1519  		}
  1520  		u0x, u0 = u0, u0+uint64(nsec)
  1521  		if u0 < u0x {
  1522  			u1++
  1523  		}
  1524  
  1525  		// Compute remainder by subtracting r<<k for decreasing k.
  1526  		// Quotient parity is whether we subtract on last round.
  1527  		d1 := uint64(d)
  1528  		for d1>>63 != 1 {
  1529  			d1 <<= 1
  1530  		}
  1531  		d0 := uint64(0)
  1532  		for {
  1533  			qmod2 = 0
  1534  			if u1 > d1 || u1 == d1 && u0 >= d0 {
  1535  				// subtract
  1536  				qmod2 = 1
  1537  				u0x, u0 = u0, u0-d0
  1538  				if u0 > u0x {
  1539  					u1--
  1540  				}
  1541  				u1 -= d1
  1542  			}
  1543  			if d1 == 0 && d0 == uint64(d) {
  1544  				break
  1545  			}
  1546  			d0 >>= 1
  1547  			d0 |= (d1 & 1) << 63
  1548  			d1 >>= 1
  1549  		}
  1550  		r = Duration(u0)
  1551  	}
  1552  
  1553  	if neg && r != 0 {
  1554  		// If input was negative and not an exact multiple of d, we computed q, r such that
  1555  		//	q*d + r = -t
  1556  		// But the right answers are given by -(q-1), d-r:
  1557  		//	q*d + r = -t
  1558  		//	-q*d - r = t
  1559  		//	-(q-1)*d + (d - r) = t
  1560  		qmod2 ^= 1
  1561  		r = d - r
  1562  	}
  1563  	return
  1564  }
  1565  

View as plain text