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