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