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