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