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