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