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