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 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664
/*!
Routines for interacting with time zones and the zoneinfo database.
The main type in this module is [`TimeZone`]. For most use cases, you may not
even need to interact with this type at all. For example, this code snippet
converts a civil datetime to a zone aware datetime:
```
use jiff::civil::date;
let zdt = date(2024, 7, 10).at(20, 48, 0, 0).intz("America/New_York")?;
assert_eq!(zdt.to_string(), "2024-07-10T20:48:00-04:00[America/New_York]");
# Ok::<(), Box<dyn std::error::Error>>(())
```
And this example parses a zone aware datetime from a string:
```
use jiff::Zoned;
let zdt: Zoned = "2024-07-10 20:48[america/new_york]".parse()?;
assert_eq!(zdt.year(), 2024);
assert_eq!(zdt.month(), 7);
assert_eq!(zdt.day(), 10);
assert_eq!(zdt.hour(), 20);
assert_eq!(zdt.minute(), 48);
assert_eq!(zdt.offset().seconds(), -4 * 60 * 60);
assert_eq!(zdt.time_zone().iana_name(), Some("America/New_York"));
# Ok::<(), Box<dyn std::error::Error>>(())
```
Yet, neither of the above examples require uttering [`TimeZone`]. This is
because the datetime types in this crate provide higher level abstractions for
working with time zone identifiers. Nevertheless, sometimes it is useful to
work with a `TimeZone` directly. For example, if one has a `TimeZone`, then
conversion from a [`Timestamp`] to a [`Zoned`] is infallible:
```
use jiff::{tz::TimeZone, Timestamp, Zoned};
let tz = TimeZone::get("America/New_York")?;
let ts = Timestamp::UNIX_EPOCH;
let zdt = ts.to_zoned(tz);
assert_eq!(zdt.to_string(), "1969-12-31T19:00:00-05:00[America/New_York]");
# Ok::<(), Box<dyn std::error::Error>>(())
```
# The [IANA Time Zone Database]
Since a time zone is a set of rules for determining the civil time, via an
offset from UTC, in a particular geographic region, a database is required to
represent the full complexity of these rules in practice. The standard database
is widespread use is the [IANA Time Zone Database]. On Unix systems, this is
typically found at `/usr/share/zoneinfo`, and Jiff will read it automatically.
On Windows systems, there is no canonical Time Zone Database installation, and
so Jiff embeds it into the compiled artifact. (This does not happen on Unix
by default.)
See the [`TimeZoneDatabase`] for more information.
# The system or "local" time zone
In many cases, the operating system manages a "default" time zone. It might,
for example, be how the `date` program converts a Unix timestamp to a time that
is "local" to you.
Unfortunately, there is no universal approach to discovering a system's default
time zone. Instead, Jiff uses heuristics like reading `/etc/localtime` on Unix,
and calling [`GetDynamicTimeZoneInformation`] on Windows. But in all cases,
Jiff will always use the IANA Time Zone Database for implementing time zone
transition rules. (For example, Windows specific APIs for time zone transitions
are not supported by Jiff.)
Moreover, Jiff supports reading the `TZ` environment variable, as specified
by POSIX, on all systems.
TO get the system's default time zone, use [`TimeZone::system`].
[IANA Time Zone Database]: https://en.wikipedia.org/wiki/Tz_database
[`GetDynamicTimeZoneInformation`]: https://learn.microsoft.com/en-us/windows/win32/api/timezoneapi/nf-timezoneapi-getdynamictimezoneinformation
*/
use alloc::{
boxed::Box,
string::{String, ToString},
sync::Arc,
};
use crate::{
civil::DateTime,
error::{err, Error, ErrorContext},
Timestamp, Zoned,
};
use self::{posix::ReasonablePosixTimeZone, tzif::Tzif};
pub use self::{
db::{db, TimeZoneDatabase, TimeZoneNameIter},
offset::{Dst, Offset, OffsetConflict},
};
mod db;
mod offset;
mod posix;
#[cfg(feature = "tz-system")]
mod system;
#[cfg(test)]
mod testdata;
mod tzif;
// See module comment for WIP status. :-(
#[cfg(test)]
mod zic;
/// A representation of a [time zone].
///
/// A time zone is a set of rules for determining the civil time, via an offset
/// from UTC, in a particular geographic region. In many cases, the offset
/// in a particular time zone can vary over the course of a year through
/// transitions into and out of [daylight saving time].
///
/// A `TimeZone` can be one of three possible representations:
///
/// * An identifier from the [IANA Time Zone Database] and the rules associated
/// with that identifier.
/// * A fixed offset where there are never any time zone transitions.
/// * A [POSIX TZ] string that specifies a standard offset and an optional
/// daylight saving time offset along with a rule for when DST is in effect.
/// The rule applies for every year. Since POSIX TZ strings cannot capture the
/// full complexity of time zone rules, they generally should not be used.
///
/// The most practical and useful representation is an IANA time zone. Namely,
/// it enjoys broad support and its database is regularly updated to reflect
/// real changes in time zone rules throughout the world. On Unix systems,
/// the time zone database is typically found at `/usr/share/zoneinfo`. For
/// more information on how Jiff interacts with The Time Zone Database, see
/// [`TimeZoneDatabase`].
///
/// In typical usage, users of Jiff shouldn't need to reference a `TimeZone`
/// directly. Instead, there are convenience APIs on datetime types that accept
/// IANA time zone identifiers and do automatic database lookups for you. For
/// example, to convert a timestamp to a zone aware datetime:
///
/// ```
/// use jiff::Timestamp;
///
/// let ts = Timestamp::from_second(1_456_789_123)?;
/// let zdt = ts.intz("America/New_York")?;
/// assert_eq!(zdt.to_string(), "2016-02-29T18:38:43-05:00[America/New_York]");
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// Or to convert a civil datetime to a zoned datetime corresponding to a
/// precise instant in time:
///
/// ```
/// use jiff::civil::date;
///
/// let dt = date(2024, 7, 15).at(21, 27, 0, 0);
/// let zdt = dt.intz("America/New_York")?;
/// assert_eq!(zdt.to_string(), "2024-07-15T21:27:00-04:00[America/New_York]");
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// Or even converted a zoned datetime from one time zone to another:
///
/// ```
/// use jiff::civil::date;
///
/// let dt = date(2024, 7, 15).at(21, 27, 0, 0);
/// let zdt1 = dt.intz("America/New_York")?;
/// let zdt2 = zdt1.intz("Israel")?;
/// assert_eq!(zdt2.to_string(), "2024-07-16T04:27:00+03:00[Israel]");
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # The system time zone
///
/// The system time zone can be retrieved via [`TimeZone::system`]. If it
/// couldn't be detected or if the `tz-system` crate feature is not enabled,
/// then [`TimeZone::UTC`] is returned. `TimeZone::system` is what's used
/// internally for retrieving the current zoned datetime via [`Zoned::now`].
///
/// While there is no platform independent way to detect your system's
/// "default" time zone, Jiff employs best-effort heuristics to determine it.
/// (For example, by examining `/etc/localtime` on Unix systems.) When the
/// heuristics fail, Jiff will emit a `WARN` level log. It can be viewed by
/// installing a `log` compatible logger, such as [`env_logger`].
///
/// # Custom time zones
///
/// At present, Jiff doesn't provide any APIs for manually constructing a
/// custom time zone. However, [`TimeZone::tzif`] is provided for reading
/// any valid TZif formatted data, as specified by [RFC 8536]. This provides
/// an interoperable way of utilizing custom time zone rules.
///
/// # A `TimeZone` is immutable
///
/// Once a `TimeZone` is created, it is immutable. That is, its underlying
/// time zone transition rules will never change. This is true for system time
/// zones or even if the IANA Time Zone Database it was loaded from changes on
/// disk. The only way such changes can be observed is by re-requesting the
/// `TimeZone` from a `TimeZoneDatabase`. (Or, in the case of the system time
/// zone, by calling `TimeZone::system`.)
///
/// # Time zone equality
///
/// `TimeZone` provides an imperfect notion of equality. That is, when two time
/// zones are equal, then it is guaranteed for them to have the same rules.
/// However, two time zones may compare unequal and yet still have the same
/// rules.
///
/// The equality semantics are as follows:
///
/// * Two fixed offset time zones are equal when their offsets are equal.
/// * Two POSIX time zones are equal when their original rule strings are
/// byte-for-byte identical.
/// * Two IANA time zones are equal when their identifiers are equal _and_
/// checksums of their rules are equal.
/// * In all other cases, time zones are unequal.
///
/// Time zone equality is, for example, used in APIs like [`Zoned::since`]
/// when asking for spans with calendar units. Namely, since days can be of
/// different lengths in different time zones, `Zoned::since` will return an
/// error when the two zoned datetimes are in different time zones and when
/// the caller requests units greater than hours.
///
/// # Dealing with ambiguity
///
/// The principal job of a `TimeZone` is to provide two different
/// transformations:
///
/// * A conversion from a [`Timestamp`] to a civil time (also known as local,
/// naive or plain time). This conversion is always unambiguous. That is,
/// there is always precisely one representation of civil time for any
/// particular instant in time for a particular time zone.
/// * A conversion from a [`civil::DateTime`](crate::civil::DateTime) to an
/// instant in time. This conversion is sometimes ambiguous in that a civil
/// time might have either never appear on the clocks in a particular
/// time zone (a gap), or in that the civil time may have been repeated on the
/// clocks in a particular time zone (a fold). Typically, a transition to
/// daylight saving time is a gap, while a transition out of daylight saving
/// time is a fold.
///
/// The timestamp-to-civil time conversion is done via
/// [`TimeZone::to_datetime`], or its lower level counterpart,
/// [`TimeZone::to_offset`]. The civil time-to-timestamp conversion is done
/// via one of the following routines:
///
/// * [`TimeZone::to_zoned`] conveniently returns a [`Zoned`] and automatically
/// uses the [`Disambiguation::Compatible`] strategy if the given civil
/// datetime is ambiguous in the time zone.
/// * [`TimeZone::to_ambiguous_zoned`] returns a potentially ambiguous
/// zoned datetime, [`AmbiguousZoned`], and provides fine-grained control over
/// how to resolve ambiguity, if it occurs.
/// * [`TimeZone::to_timestamp`] is like `TimeZone::to_zoned`, but returns
/// a [`Timestamp`] instead.
/// * [`TimeZone::to_ambiguous_timestamp`] is like
/// `TimeZone::to_ambiguous_zoned`, but returns an [`AmbiguousTimestamp`]
/// instead.
///
/// Here is an example where we explore the different disambiguation strategies
/// for a fold in time, where in this case, the 1 o'clock hour is repeated:
///
/// ```
/// use jiff::{civil::date, tz::TimeZone};
///
/// let tz = TimeZone::get("America/New_York")?;
/// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
/// // It's ambiguous, so asking for an unambiguous instant presents an error!
/// assert!(tz.to_ambiguous_zoned(dt).unambiguous().is_err());
/// // Gives you the earlier time in a fold, i.e., before DST ends:
/// assert_eq!(
/// tz.to_ambiguous_zoned(dt).earlier()?.to_string(),
/// "2024-11-03T01:30:00-04:00[America/New_York]",
/// );
/// // Gives you the later time in a fold, i.e., after DST ends.
/// // Notice the offset change from the previous example!
/// assert_eq!(
/// tz.to_ambiguous_zoned(dt).later()?.to_string(),
/// "2024-11-03T01:30:00-05:00[America/New_York]",
/// );
/// // "Just give me something reasonable"
/// assert_eq!(
/// tz.to_ambiguous_zoned(dt).compatible()?.to_string(),
/// "2024-11-03T01:30:00-04:00[America/New_York]",
/// );
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// [time zone]: https://en.wikipedia.org/wiki/Time_zone
/// [daylight saving time]: https://en.wikipedia.org/wiki/Daylight_saving_time
/// [IANA Time Zone Database]: https://en.wikipedia.org/wiki/Tz_database
/// [POSIX TZ]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html
/// [`env_logger`]: https://docs.rs/env_logger
/// [RFC 8536]: https://datatracker.ietf.org/doc/html/rfc8536
#[derive(Clone, Eq, PartialEq)]
pub struct TimeZone {
kind: Option<Arc<TimeZoneKind>>,
}
impl TimeZone {
/// The UTC time zone.
///
/// The offset of this time is `0` and never has any transitions.
pub const UTC: TimeZone = TimeZone { kind: None };
/// Returns the system configured time zone, if available.
///
/// If the system's default time zone could not be determined, or if
/// the `tz-system` crate feature is not enabled, then this returns
/// [`TimeZone::UTC`]. A `WARN` level log will also be emitted with a
/// message explaining why time zone detection failed.
///
/// Detection of a system's default time zone is generally heuristic
/// based and platform specific.
///
/// # Platform behavior
///
/// This section is a "best effort" explanation of how the time zone is
/// detected on supported platforms. The behavior is subject to change.
///
/// On all platforms, the `TZ` environment variable overrides any other
/// heuristic, and provides a way for end users to set the time zone for
/// specific use cases. In general, Jiff respects the [POSIX TZ] rules.
/// Here are some examples:
///
/// * `TZ=America/New_York` for setting a time zone via an IANA Time Zone
/// Database Identifier.
/// * `TZ=/usr/share/zoneinfo/America/New_York` for setting a time zone
/// by providing a file path to a TZif file directly.
/// * `TZ=EST5EDT,M3.2.0,M11.1.0` for setting a time zone via a daylight
/// saving time transition rule.
///
/// Otherwise, when `TZ` isn't set, then:
///
/// On Unix systems, this inspects `/etc/localtime`. If it's a symbolic
/// link to an entry in `/usr/share/zoneinfo`, then the suffix is
/// considered an IANA Time Zone Database identifier. Otherwise,
/// `/etc/localtime` is read as a TZif file directly.
///
/// On Windows, the system time zone is determined via
/// [`GetDynamicTimeZoneInformation`]. The result is then mapped to an
/// IANA Time Zone Database identifier via Unicode's
/// [CLDR XML data].
///
/// [POSIX TZ]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html
/// [`GetDynamicTimeZoneInformation`]: https://learn.microsoft.com/en-us/windows/win32/api/timezoneapi/nf-timezoneapi-getdynamictimezoneinformation
/// [CLDR XML data]: https://github.com/unicode-org/cldr/raw/main/common/supplemental/windowsZones.xml
#[inline]
pub fn system() -> TimeZone {
#[cfg(not(feature = "tz-system"))]
{
warn!(
"failed to get system time zone since 'system', \
crate feature is not enabled, falling back to UTC",
);
TimeZone::UTC
}
#[cfg(feature = "tz-system")]
{
match self::system::get(db()) {
Ok(tz) => tz,
Err(_err) => {
warn!(
"failed to get system time zone, \
falling back to UTC: {_err}",
);
TimeZone::UTC
}
}
}
}
/// A convenience function for performing a time zone database lookup for
/// the given time zone identifier. It uses the default global time zone
/// database via [`tz::db()`](db()).
///
/// # Errors
///
/// This returns an error if the given time zone identifier could not be
/// found in the default [`TimeZoneDatabase`].
///
/// # Example
///
/// ```
/// use jiff::{tz::TimeZone, Timestamp};
///
/// let tz = TimeZone::get("Japan")?;
/// assert_eq!(
/// tz.to_datetime(Timestamp::UNIX_EPOCH).to_string(),
/// "1970-01-01T09:00:00",
/// );
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn get(time_zone_name: &str) -> Result<TimeZone, Error> {
db().get(time_zone_name)
}
/// Returns a time zone with a fixed offset.
///
/// A fixed offset will never have any transitions and won't follow any
/// particular time zone rules. In general, one should avoid using fixed
/// offset time zones unless you have a specific need for them. Otherwise,
/// IANA time zones via [`TimeZone::get`] should be preferred, as they
/// more accurately model the actual time zone transitions rules used in
/// practice.
///
/// # Example
///
/// ```
/// use jiff::{tz::{self, TimeZone}, Timestamp};
///
/// let tz = TimeZone::fixed(tz::offset(10));
/// assert_eq!(
/// tz.to_datetime(Timestamp::UNIX_EPOCH).to_string(),
/// "1970-01-01T10:00:00",
/// );
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn fixed(offset: Offset) -> TimeZone {
if offset == Offset::UTC {
return TimeZone::UTC;
}
let fixed = TimeZoneFixed::new(offset);
let kind = TimeZoneKind::Fixed(fixed);
TimeZone { kind: Some(Arc::new(kind)) }
}
/// Creates a time zone from a [POSIX TZ] rule string.
///
/// A POSIX time zone provides a way to tersely define a single daylight
/// saving time transition rule (or none at all) that applies for all
/// years.
///
/// Users should avoid using this kind of time zone unless there is a
/// specific need for it. Namely, POSIX time zones cannot capture the full
/// complexity of time zone transition rules in the real world. (See the
/// example below.)
///
/// [POSIX TZ]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html
///
/// # Errors
///
/// This returns an error if the given POSIX time zone string is invalid.
///
/// # Example
///
/// This example demonstrates how a POSIX time zone may be historically
/// inaccurate:
///
/// ```
/// use jiff::{civil::date, tz::TimeZone};
///
/// // The tzdb entry for America/New_York.
/// let iana = TimeZone::get("America/New_York")?;
/// // The POSIX TZ string for New York DST that went into effect in 2007.
/// let posix = TimeZone::posix("EST5EDT,M3.2.0,M11.1.0")?;
///
/// // New York entered DST on April 2, 2006 at 2am:
/// let dt = date(2006, 4, 2).at(2, 0, 0, 0);
/// // The IANA tzdb entry correctly reports it as ambiguous:
/// assert!(iana.to_ambiguous_timestamp(dt).is_ambiguous());
/// // But the POSIX time zone does not:
/// assert!(!posix.to_ambiguous_timestamp(dt).is_ambiguous());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn posix(posix_tz_string: &str) -> Result<TimeZone, Error> {
let posix = TimeZonePosix::new(posix_tz_string)?;
let kind = TimeZoneKind::Posix(posix);
Ok(TimeZone { kind: Some(Arc::new(kind)) })
}
/// Creates a time zone from TZif binary data, whose format is specified
/// in [RFC 8536]. All versions of TZif (up through version 4) are
/// supported.
///
/// This constructor is typically not used, and instead, one should rely
/// on time zone lookups via time zone identifiers with routines like
/// [`TimeZone::get`]. However, this constructor does provide one way
/// of using custom time zones with Jiff.
///
/// The name given should be a IANA time zone database identifier.
///
/// [RFC 8536]: https://datatracker.ietf.org/doc/html/rfc8536
///
/// # Errors
///
/// This returns an error if the given data was not recognized as valid
/// TZif.
pub fn tzif(name: &str, data: &[u8]) -> Result<TimeZone, Error> {
let tzif = TimeZoneTzif::new(Some(name.to_string()), data)?;
let kind = TimeZoneKind::Tzif(tzif);
Ok(TimeZone { kind: Some(Arc::new(kind)) })
}
/// This creates an unnamed TZif-backed `TimeZone`.
///
/// At present, the only way for an unnamed TZif-backed `TimeZone` to be
/// created is when the system time zone has no identifiable name. For
/// example, when `/etc/localtime` is hard-linked to a TZif file instead
/// of being symlinked. In this case, there is no cheap and unambiguous
/// way to determine the time zone name. So we just let it be unnamed.
/// Since this is the only such case, and hopefully will only ever be the
/// only such case, we consider such unnamed TZif-back `TimeZone` values
/// as being the "system" time zone.
///
/// When this is used to construct a `TimeZone`, the `TimeZone::name`
/// method will be "Local". This is... pretty unfortunate. I'm not sure
/// what else to do other than to make `TimeZone::name` return an
/// `Option<&str>`. But... we use it in a bunch of places and it just
/// seems bad for a time zone to not have a name.
///
/// OK, because of the above, I renamed `TimeZone::name` to
/// `TimeZone::diagnostic_name`. This should make it clearer that you can't
/// really use the name to do anything interesting. This also makes more
/// sense for POSIX TZ strings too.
///
/// In any case, this routine stays unexported because I don't want TZif
/// backed `TimeZone` values to proliferate. If you have a legitimate use
/// case otherwise, please file an issue. It will require API design.
///
/// # Errors
///
/// This returns an error if the given TZif data is invalid.
fn tzif_system(data: &[u8]) -> Result<TimeZone, Error> {
let tzif = TimeZoneTzif::new(None, data)?;
let kind = TimeZoneKind::Tzif(tzif);
Ok(TimeZone { kind: Some(Arc::new(kind)) })
}
#[inline]
pub(crate) fn diagnostic_name(&self) -> &str {
let Some(ref kind) = self.kind else { return "UTC" };
match **kind {
TimeZoneKind::Fixed(ref tz) => tz.name(),
TimeZoneKind::Posix(ref tz) => tz.name(),
TimeZoneKind::Tzif(ref tz) => tz.name().unwrap_or("Local"),
}
}
/// When this time zone was loaded from an IANA time zone database entry,
/// then this returns the canonicalized name for that time zone.
///
/// # Example
///
/// ```
/// use jiff::tz::TimeZone;
///
/// let tz = TimeZone::get("america/NEW_YORK")?;
/// assert_eq!(tz.iana_name(), Some("America/New_York"));
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn iana_name(&self) -> Option<&str> {
let Some(ref kind) = self.kind else { return Some("UTC") };
match **kind {
TimeZoneKind::Tzif(ref tz) => tz.name(),
_ => None,
}
}
/// Returns the civil datetime corresponding to the given timestamp in this
/// time zone.
///
/// This operation is always unambiguous. That is, for any instant in time
/// supported by Jiff (that is, a `Timestamp`), there is always precisely
/// one civil datetime corresponding to that instant.
///
/// Note that this is considered a lower level routine. Consider working
/// with zoned datetimes instead, and use [`Zoned::datetime`] to get its
/// civil time if necessary.
///
/// # Example
///
/// ```
/// use jiff::{tz::TimeZone, Timestamp};
///
/// let tz = TimeZone::get("Europe/Rome")?;
/// assert_eq!(
/// tz.to_datetime(Timestamp::UNIX_EPOCH).to_string(),
/// "1970-01-01T01:00:00",
/// );
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// As mentioned above, consider using `Zoned` instead:
///
/// ```
/// use jiff::{tz::TimeZone, Timestamp};
///
/// let zdt = Timestamp::UNIX_EPOCH.intz("Europe/Rome")?;
/// assert_eq!(zdt.datetime().to_string(), "1970-01-01T01:00:00");
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn to_datetime(&self, timestamp: Timestamp) -> DateTime {
let (offset, _, _) = self.to_offset(timestamp);
offset.to_datetime(timestamp)
}
/// Returns the offset corresponding to the given timestamp in this time
/// zone.
///
/// This operation is always unambiguous. That is, for any instant in time
/// supported by Jiff (that is, a `Timestamp`), there is always precisely
/// one offset corresponding to that instant.
///
/// Given an offset, one can use APIs like [`Offset::to_datetime`] to
/// create a civil datetime from a timestamp.
///
/// This also returns whether this timestamp is considered to be in
/// "daylight saving time," as well as the abbreviation for the time zone
/// at this time.
///
/// # Example
///
/// ```
/// use jiff::{tz::{self, Dst, TimeZone}, Timestamp};
///
/// let tz = TimeZone::get("America/New_York")?;
///
/// // A timestamp in DST in New York.
/// let ts = Timestamp::from_second(1_720_493_204)?;
/// let (offset, dst, abbrev) = tz.to_offset(ts);
/// assert_eq!(offset, tz::offset(-4));
/// assert_eq!(dst, Dst::Yes);
/// assert_eq!(abbrev, "EDT");
/// assert_eq!(offset.to_datetime(ts).to_string(), "2024-07-08T22:46:44");
///
/// // A timestamp *not* in DST in New York.
/// let ts = Timestamp::from_second(1_704_941_204)?;
/// let (offset, dst, abbrev) = tz.to_offset(ts);
/// assert_eq!(offset, tz::offset(-5));
/// assert_eq!(dst, Dst::No);
/// assert_eq!(abbrev, "EST");
/// assert_eq!(offset.to_datetime(ts).to_string(), "2024-01-10T21:46:44");
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn to_offset(&self, timestamp: Timestamp) -> (Offset, Dst, &str) {
let Some(ref kind) = self.kind else {
return (Offset::UTC, Dst::No, "UTC");
};
match **kind {
TimeZoneKind::Fixed(ref tz) => (tz.offset(), Dst::No, tz.name()),
TimeZoneKind::Posix(ref tz) => tz.to_offset(timestamp),
TimeZoneKind::Tzif(ref tz) => tz.to_offset(timestamp),
}
}
/// Converts a civil datetime to a [`Zoned`] in this time zone.
///
/// The given civil datetime may be ambiguous in this time zone. A civil
/// datetime is ambiguous when either of the following occurs:
///
/// * When the civil datetime falls into a "gap." That is, when there is a
/// jump forward in time where a span of time does not appear on the clocks
/// in this time zone. This _typically_ manifests as a 1 hour jump forward
/// into daylight saving time.
/// * When the civil datetime falls into a "fold." That is, when there is
/// a jump backward in time where a span of time is _repeated_ on the
/// clocks in this time zone. This _typically_ manifests as a 1 hour jump
/// backward out of daylight saving time.
///
/// This routine automatically resolves both of the above ambiguities via
/// the [`Disambiguation::Compatible`] strategy. That in, the case of a
/// gap, the time after the gap is used. In the case of a fold, the first
/// repetition of the clock time is used.
///
/// # Example
///
/// This example shows how disambiguation works:
///
/// ```
/// use jiff::{civil::date, tz::TimeZone};
///
/// let tz = TimeZone::get("America/New_York")?;
///
/// // This demonstrates disambiguation behavior for a gap.
/// let zdt = tz.to_zoned(date(2024, 3, 10).at(2, 30, 0, 0))?;
/// assert_eq!(zdt.to_string(), "2024-03-10T03:30:00-04:00[America/New_York]");
/// // This demonstrates disambiguation behavior for a fold.
/// // Notice the offset: the -04 corresponds to the time while
/// // still in DST. The second repetition of the 1 o'clock hour
/// // occurs outside of DST, in "standard" time, with the offset -5.
/// let zdt = tz.to_zoned(date(2024, 11, 3).at(1, 30, 0, 0))?;
/// assert_eq!(zdt.to_string(), "2024-11-03T01:30:00-04:00[America/New_York]");
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn to_zoned(&self, dt: DateTime) -> Result<Zoned, Error> {
self.to_ambiguous_zoned(dt).compatible()
}
/// Converts a civil datetime to a possibly ambiguous zoned datetime in
/// this time zone.
///
/// The given civil datetime may be ambiguous in this time zone. A civil
/// datetime is ambiguous when either of the following occurs:
///
/// * When the civil datetime falls into a "gap." That is, when there is a
/// jump forward in time where a span of time does not appear on the clocks
/// in this time zone. This _typically_ manifests as a 1 hour jump forward
/// into daylight saving time.
/// * When the civil datetime falls into a "fold." That is, when there is
/// a jump backward in time where a span of time is _repeated_ on the
/// clocks in this time zone. This _typically_ manifests as a 1 hour jump
/// backward out of daylight saving time.
///
/// Unlike [`TimeZone::to_zoned`], this method does not do any automatic
/// disambiguation. Instead, callers are expected to use the methods on
/// [`AmbiguousZoned`] to resolve any ambiguity, if it occurs.
///
/// # Example
///
/// This example shows how to return an error when the civil datetime given
/// is ambiguous:
///
/// ```
/// use jiff::{civil::date, tz::TimeZone};
///
/// let tz = TimeZone::get("America/New_York")?;
///
/// // This is not ambiguous:
/// let dt = date(2024, 3, 10).at(1, 0, 0, 0);
/// assert_eq!(
/// tz.to_ambiguous_zoned(dt).unambiguous()?.to_string(),
/// "2024-03-10T01:00:00-05:00[America/New_York]",
/// );
/// // But this is a gap, and thus ambiguous! So an error is returned.
/// let dt = date(2024, 3, 10).at(2, 0, 0, 0);
/// assert!(tz.to_ambiguous_zoned(dt).unambiguous().is_err());
/// // And so is this, because it's a fold.
/// let dt = date(2024, 11, 3).at(1, 0, 0, 0);
/// assert!(tz.to_ambiguous_zoned(dt).unambiguous().is_err());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn to_ambiguous_zoned(&self, dt: DateTime) -> AmbiguousZoned {
self.clone().into_ambiguous_zoned(dt)
}
/// Converts a civil datetime to a possibly ambiguous zoned datetime in
/// this time zone, and does so by assuming ownership of this `TimeZone`.
///
/// This is identical to [`TimeZone::to_ambiguous_zoned`], but it avoids
/// a `TimeZone::clone()` call. (Which are cheap, but not completely free.)
///
/// # Example
///
/// This example shows how to create a `Zoned` value from a `TimeZone`
/// and a `DateTime` without cloning the `TimeZone`:
///
/// ```
/// use jiff::{civil::date, tz::TimeZone};
///
/// let tz = TimeZone::get("America/New_York")?;
/// let dt = date(2024, 3, 10).at(1, 0, 0, 0);
/// assert_eq!(
/// tz.into_ambiguous_zoned(dt).unambiguous()?.to_string(),
/// "2024-03-10T01:00:00-05:00[America/New_York]",
/// );
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn into_ambiguous_zoned(self, dt: DateTime) -> AmbiguousZoned {
self.to_ambiguous_timestamp(dt).into_ambiguous_zoned(self)
}
/// Converts a civil datetime to a [`Timestamp`] in this time zone.
///
/// The given civil datetime may be ambiguous in this time zone. A civil
/// datetime is ambiguous when either of the following occurs:
///
/// * When the civil datetime falls into a "gap." That is, when there is a
/// jump forward in time where a span of time does not appear on the clocks
/// in this time zone. This _typically_ manifests as a 1 hour jump forward
/// into daylight saving time.
/// * When the civil datetime falls into a "fold." That is, when there is
/// a jump backward in time where a span of time is _repeated_ on the
/// clocks in this time zone. This _typically_ manifests as a 1 hour jump
/// backward out of daylight saving time.
///
/// This routine automatically resolves both of the above ambiguities via
/// the [`Disambiguation::Compatible`] strategy. That in, the case of a
/// gap, the time after the gap is used. In the case of a fold, the first
/// repetition of the clock time is used.
///
/// This routine is identical to [`TimeZone::to_zoned`], except it returns
/// a `Timestamp` instead of a zoned datetime. The benefit of this
/// method is that it never requires cloning or consuming ownership of a
/// `TimeZone`, and it doesn't require construction of `Zoned` which has
/// a small but non-zero cost. (This is partially because a `Zoned` value
/// contains a `TimeZone`, but of course, a `Timestamp` does not.)
///
/// # Example
///
/// This example shows how disambiguation works:
///
/// ```
/// use jiff::{civil::date, tz::TimeZone};
///
/// let tz = TimeZone::get("America/New_York")?;
///
/// // This demonstrates disambiguation behavior for a gap.
/// let ts = tz.to_timestamp(date(2024, 3, 10).at(2, 30, 0, 0))?;
/// assert_eq!(ts.to_string(), "2024-03-10T07:30:00Z");
/// // This demonstrates disambiguation behavior for a fold.
/// // Notice the offset: the -04 corresponds to the time while
/// // still in DST. The second repetition of the 1 o'clock hour
/// // occurs outside of DST, in "standard" time, with the offset -5.
/// let ts = tz.to_timestamp(date(2024, 11, 3).at(1, 30, 0, 0))?;
/// assert_eq!(ts.to_string(), "2024-11-03T05:30:00Z");
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn to_timestamp(&self, dt: DateTime) -> Result<Timestamp, Error> {
self.to_ambiguous_timestamp(dt).compatible()
}
/// Converts a civil datetime to a possibly ambiguous timestamp in
/// this time zone.
///
/// The given civil datetime may be ambiguous in this time zone. A civil
/// datetime is ambiguous when either of the following occurs:
///
/// * When the civil datetime falls into a "gap." That is, when there is a
/// jump forward in time where a span of time does not appear on the clocks
/// in this time zone. This _typically_ manifests as a 1 hour jump forward
/// into daylight saving time.
/// * When the civil datetime falls into a "fold." That is, when there is
/// a jump backward in time where a span of time is _repeated_ on the
/// clocks in this time zone. This _typically_ manifests as a 1 hour jump
/// backward out of daylight saving time.
///
/// Unlike [`TimeZone::to_timestamp`], this method does not do any
/// automatic disambiguation. Instead, callers are expected to use the
/// methods on [`AmbiguousTimestamp`] to resolve any ambiguity, if it
/// occurs.
///
/// This routine is identical to [`TimeZone::to_ambiguous_zoned`], except
/// it returns an `AmbiguousTimestamp` instead of a `AmbiguousZoned`. The
/// benefit of this method is that it never requires cloning or consuming
/// ownership of a `TimeZone`, and it doesn't require construction of
/// `Zoned` which has a small but non-zero cost. (This is partially because
/// a `Zoned` value contains a `TimeZone`, but of course, a `Timestamp`
/// does not.)
///
/// # Example
///
/// This example shows how to return an error when the civil datetime given
/// is ambiguous:
///
/// ```
/// use jiff::{civil::date, tz::TimeZone};
///
/// let tz = TimeZone::get("America/New_York")?;
///
/// // This is not ambiguous:
/// let dt = date(2024, 3, 10).at(1, 0, 0, 0);
/// assert_eq!(
/// tz.to_ambiguous_timestamp(dt).unambiguous()?.to_string(),
/// "2024-03-10T06:00:00Z",
/// );
/// // But this is a gap, and thus ambiguous! So an error is returned.
/// let dt = date(2024, 3, 10).at(2, 0, 0, 0);
/// assert!(tz.to_ambiguous_timestamp(dt).unambiguous().is_err());
/// // And so is this, because it's a fold.
/// let dt = date(2024, 11, 3).at(1, 0, 0, 0);
/// assert!(tz.to_ambiguous_timestamp(dt).unambiguous().is_err());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn to_ambiguous_timestamp(&self, dt: DateTime) -> AmbiguousTimestamp {
let ambiguous_kind = match self.kind {
None => AmbiguousOffset::Unambiguous { offset: Offset::UTC },
Some(ref kind) => match **kind {
TimeZoneKind::Fixed(ref tz) => {
AmbiguousOffset::Unambiguous { offset: tz.offset() }
}
TimeZoneKind::Posix(ref tz) => tz.to_ambiguous_kind(dt),
TimeZoneKind::Tzif(ref tz) => tz.to_ambiguous_kind(dt),
},
};
AmbiguousTimestamp::new(dt, ambiguous_kind)
}
// I'd like to export the prev/next transition routines below, but I'm
// not fully sure of their API. I'd like to understand use cases a bit
// better. And I suspect it would make more sense to not just return a
// timestamp, but also the offset associated with the time zone transition
// change. Otherwise, if one needs the offset, you need to go back and do
// another lookup via `TimeZone::to_offset`. Where as I believe finding the
// prev/next transition must also necessarily find the offset too. So we
// might as well return it.
#[allow(dead_code)]
#[inline]
fn previous_transition(&self, timestamp: Timestamp) -> Option<Timestamp> {
match **self.kind.as_ref()? {
TimeZoneKind::Fixed(_) => None,
TimeZoneKind::Posix(ref tz) => tz.previous_transition(timestamp),
TimeZoneKind::Tzif(ref tz) => tz.previous_transition(timestamp),
}
}
#[allow(dead_code)]
#[inline]
fn next_transition(&self, timestamp: Timestamp) -> Option<Timestamp> {
match **self.kind.as_ref()? {
TimeZoneKind::Fixed(_) => None,
TimeZoneKind::Posix(ref tz) => tz.next_transition(timestamp),
TimeZoneKind::Tzif(ref tz) => tz.next_transition(timestamp),
}
}
}
impl core::fmt::Debug for TimeZone {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
let field: &dyn core::fmt::Debug = match self.kind {
None => &"UTC",
Some(ref kind) => match &**kind {
TimeZoneKind::Fixed(ref tz) => tz,
TimeZoneKind::Posix(ref tz) => tz,
TimeZoneKind::Tzif(ref tz) => tz,
},
};
f.debug_tuple("TimeZone").field(field).finish()
}
}
#[derive(Debug, Eq, PartialEq)]
enum TimeZoneKind {
Fixed(TimeZoneFixed),
Posix(TimeZonePosix),
Tzif(TimeZoneTzif),
}
#[derive(Clone)]
struct TimeZoneFixed {
offset: Offset,
name: Box<str>,
}
impl TimeZoneFixed {
#[inline]
fn new(offset: Offset) -> TimeZoneFixed {
let name = offset.to_string().into();
TimeZoneFixed { offset, name }
}
#[inline]
fn name(&self) -> &str {
&self.name
}
#[inline]
fn offset(&self) -> Offset {
self.offset
}
}
impl core::fmt::Debug for TimeZoneFixed {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_tuple("Fixed").field(&self.offset()).finish()
}
}
impl Eq for TimeZoneFixed {}
impl PartialEq for TimeZoneFixed {
#[inline]
fn eq(&self, rhs: &TimeZoneFixed) -> bool {
self.offset() == rhs.offset()
}
}
#[derive(Eq, PartialEq)]
struct TimeZonePosix {
name: Box<str>,
posix: ReasonablePosixTimeZone,
}
impl TimeZonePosix {
#[inline]
fn new(s: &str) -> Result<TimeZonePosix, Error> {
let iana_tz = posix::IanaTz::parse_v3plus(s)?;
Ok(TimeZonePosix::from(iana_tz.into_tz()))
}
#[inline]
fn name(&self) -> &str {
&self.name
}
#[inline]
fn to_offset(&self, timestamp: Timestamp) -> (Offset, Dst, &str) {
self.posix.to_offset(timestamp)
}
#[inline]
fn to_ambiguous_kind(&self, dt: DateTime) -> AmbiguousOffset {
self.posix.to_ambiguous_kind(dt)
}
#[inline]
fn previous_transition(&self, timestamp: Timestamp) -> Option<Timestamp> {
self.posix.previous_transition(timestamp)
}
#[inline]
fn next_transition(&self, timestamp: Timestamp) -> Option<Timestamp> {
self.posix.next_transition(timestamp)
}
}
impl From<ReasonablePosixTimeZone> for TimeZonePosix {
#[inline]
fn from(posix: ReasonablePosixTimeZone) -> TimeZonePosix {
let name = posix.as_str().to_string().into();
TimeZonePosix { name, posix }
}
}
// This is implemented by hand because dumping out the full representation of
// a `ReasonablePosixTimeZone` is way too much noise for users of Jiff.
impl core::fmt::Debug for TimeZonePosix {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_tuple("Posix").field(&self.posix.as_str()).finish()
}
}
#[derive(Eq, PartialEq)]
struct TimeZoneTzif {
tzif: Tzif,
}
impl TimeZoneTzif {
#[inline]
fn new(name: Option<String>, bytes: &[u8]) -> Result<TimeZoneTzif, Error> {
let tzif = Tzif::parse(name, bytes)?;
Ok(TimeZoneTzif { tzif })
}
#[inline]
fn name(&self) -> Option<&str> {
self.tzif.name()
}
#[inline]
fn to_offset(&self, timestamp: Timestamp) -> (Offset, Dst, &str) {
self.tzif.to_offset(timestamp)
}
#[inline]
fn to_ambiguous_kind(&self, dt: DateTime) -> AmbiguousOffset {
self.tzif.to_ambiguous_kind(dt)
}
#[inline]
fn previous_transition(&self, timestamp: Timestamp) -> Option<Timestamp> {
self.tzif.previous_transition(timestamp)
}
#[inline]
fn next_transition(&self, timestamp: Timestamp) -> Option<Timestamp> {
self.tzif.next_transition(timestamp)
}
}
// This is implemented by hand because dumping out the full representation of
// all TZif data is too much noise for users of Jiff.
impl core::fmt::Debug for TimeZoneTzif {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_tuple("TZif").field(&self.name().unwrap_or("Local")).finish()
}
}
/// Configuration for resolving ambiguous datetimes in a particular time zone.
///
/// This is useful for specifying how to disambiguate ambiguous datetimes at
/// runtime. For example, as configuration for parsing [`Zoned`] values via
/// [`fmt::temporal::DateTimeParser::disambiguation`](crate::fmt::temporal::DateTimeParser::disambiguation).
///
/// Note that there is no difference in using
/// `Disambiguation::Compatible.disambiguate(ambiguous_timestamp)` and
/// `ambiguous_timestamp.compatible()`. They are equivalent. The purpose of
/// this enum is to expose the disambiguation strategy as a runtime value for
/// configuration purposes.
///
/// The default value is `Disambiguation::Compatible`, which matches the
/// behavior specified in [RFC 5545 (iCalendar)]. Namely, when an ambiguous
/// datetime is found in a fold (the clocks are rolled back), then the earlier
/// time is selected. And when an ambiguous datetime is found in a gap (the
/// clocks are skipped forward), then the later time is selected.
///
/// This enum is non-exhaustive so that other forms of disambiguation may be
/// added in semver compatible releases.
///
/// [RFC 5545 (iCalendar)]: https://datatracker.ietf.org/doc/html/rfc5545
///
/// # Example
///
/// This example shows the default disambiguation mode ("compatible") when
/// given a datetime that falls in a "gap" (i.e., a forwards DST transition).
///
/// ```
/// use jiff::{civil::date, tz};
///
/// let newyork = tz::db().get("America/New_York")?;
/// let ambiguous = newyork.to_ambiguous_zoned(date(2024, 3, 10).at(2, 30, 0, 0));
///
/// // NOTE: This is identical to `ambiguous.compatible()`.
/// let zdt = ambiguous.disambiguate(tz::Disambiguation::Compatible)?;
/// assert_eq!(zdt.datetime(), date(2024, 3, 10).at(3, 30, 0, 0));
/// // In compatible mode, forward transitions select the later
/// // time. In the EST->EDT transition, that's the -04 (EDT) offset.
/// assert_eq!(zdt.offset(), tz::offset(-4));
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Example: parsing
///
/// This example shows how to set the disambiguation configuration while
/// parsing a [`Zoned`] datetime. In this example, we always prefer the earlier
/// time.
///
/// ```
/// use jiff::{civil::date, fmt::temporal::DateTimeParser, tz};
///
/// static PARSER: DateTimeParser = DateTimeParser::new()
/// .disambiguation(tz::Disambiguation::Earlier);
///
/// let zdt = PARSER.parse_zoned("2024-03-10T02:30[America/New_York]")?;
/// // In earlier mode, forward transitions select the earlier time, unlike
/// // in compatible mode. In this case, that's the pre-DST offset of -05.
/// assert_eq!(zdt.datetime(), date(2024, 3, 10).at(1, 30, 0, 0));
/// assert_eq!(zdt.offset(), tz::offset(-5));
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Copy, Debug, Default)]
#[non_exhaustive]
pub enum Disambiguation {
/// In a backward transition, the earlier time is selected. In forward
/// transition, the later time is selected.
///
/// This is equivalent to [`AmbiguousTimestamp::compatible`] and
/// [`AmbiguousZoned::compatible`].
#[default]
Compatible,
/// The earlier time is always selected.
///
/// This is equivalent to [`AmbiguousTimestamp::earlier`] and
/// [`AmbiguousZoned::earlier`].
Earlier,
/// The later time is always selected.
///
/// This is equivalent to [`AmbiguousTimestamp::later`] and
/// [`AmbiguousZoned::later`].
Later,
/// When an ambiguous datetime is encountered, this strategy will always
/// result in an error. This is useful if you need to require datetimes
/// from users to unambiguously refer to a specific instant.
///
/// This is equivalent to [`AmbiguousTimestamp::unambiguous`] and
/// [`AmbiguousZoned::unambiguous`].
Reject,
}
/// A possibly ambiguous [`Offset`].
///
/// An `AmbiguousOffset` is part of both [`AmbiguousTimestamp`] and
/// [`AmbiguousZoned`], which are created by
/// [`TimeZone::to_ambiguous_timestamp`] and
/// [`TimeZone::to_ambiguous_zoned`], respectively.
///
/// When converting a civil datetime in a particular time zone to a precise
/// instant in time (that is, either `Timestamp` or `Zoned`), then the primary
/// thing needed to form a precise instant in time is an [`Offset`]. The
/// problem is that some civil datetimes are ambiguous. That is, some do not
/// exist (because they fall into a gap, where some civil time is skipped),
/// or some are repeated (because they fall into a fold, where some civil time
/// is repeated).
///
/// The purpose of this type is to represent that ambiguity when it occurs.
/// The ambiguity is manifest through the offset choice: it is either the
/// offset _before_ the transition or the offset _after_ the transition. This
/// is true regardless of whether the ambiguity occurs as a result of a gap
/// or a fold.
///
/// It is generally considered very rare to need to inspect values of this
/// type directly. Instead, higher level routines like
/// [`AmbiguousZoned::compatible`] or [`AmbiguousZoned::unambiguous`] will
/// implement a strategy for you.
///
/// # Example
///
/// This example shows how the "compatible" disambiguation strategy is
/// implemented. Recall that the "compatible" strategy chooses the offset
/// corresponding to the civil datetime after a gap, and the offset
/// corresponding to the civil datetime before a gap.
///
/// ```
/// use jiff::{civil::date, tz::{self, AmbiguousOffset}};
///
/// let tz = tz::db().get("America/New_York")?;
/// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
/// let offset = match tz.to_ambiguous_timestamp(dt).offset() {
/// AmbiguousOffset::Unambiguous { offset } => offset,
/// // This is counter-intuitive, but in order to get the civil datetime
/// // *after* the gap, we need to select the offset from *before* the
/// // gap.
/// AmbiguousOffset::Gap { before, .. } => before,
/// AmbiguousOffset::Fold { before, .. } => before,
/// };
/// assert_eq!(offset.to_timestamp(dt)?.to_string(), "2024-03-10T07:30:00Z");
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AmbiguousOffset {
/// The offset for a particular civil datetime and time zone is
/// unambiguous.
///
/// This is the overwhelmingly common case. In general, the only time this
/// case does not occur is when there is a transition to a different time
/// zone (rare) or to/from daylight saving time (occurs for 1 hour twice
/// in year in many geographic locations).
Unambiguous {
/// The offset from UTC for the corresponding civil datetime given. The
/// offset is determined via the relevant time zone data, and in this
/// case, there is only one possible offset that could be applied to
/// the given civil datetime.
offset: Offset,
},
/// The offset for a particular civil datetime and time zone is ambiguous
/// because there is a gap.
///
/// This most commonly occurs when a civil datetime corresponds to an hour
/// that was "skipped" in a jump to DST (daylight saving time).
Gap {
/// The offset corresponding to the time before a gap.
///
/// For example, given a time zone of `America/Los_Angeles`, the offset
/// for time immediately preceding `2020-03-08T02:00:00` is `-08`.
before: Offset,
/// The offset corresponding to the later time in a gap.
///
/// For example, given a time zone of `America/Los_Angeles`, the offset
/// for time immediately following `2020-03-08T02:59:59` is `-07`.
after: Offset,
},
/// The offset for a particular civil datetime and time zone is ambiguous
/// because there is a fold.
///
/// This most commonly occurs when a civil datetime corresponds to an hour
/// that was "repeated" in a jump to standard time from DST (daylight
/// saving time).
Fold {
/// The offset corresponding to the earlier time in a fold.
///
/// For example, given a time zone of `America/Los_Angeles`, the offset
/// for time on the first `2020-11-01T01:00:00` is `-07`.
before: Offset,
/// The offset corresponding to the earlier time in a fold.
///
/// For example, given a time zone of `America/Los_Angeles`, the offset
/// for time on the second `2020-11-01T01:00:00` is `-08`.
after: Offset,
},
}
/// A possibly ambiguous [`Timestamp`], created by
/// [`TimeZone::to_ambiguous_timestamp`].
///
/// While this is called an ambiguous _timestamp_, the thing that is
/// actually ambiguous is the offset. That is, an ambiguous timestamp is
/// actually a pair of a [`civil::DateTime`](crate::civil::DateTime) and an
/// [`AmbiguousOffset`].
///
/// When the offset is ambiguous, it either represents a gap (civil time is
/// skipped) or a fold (civil time is repeated). In both cases, there are, by
/// construction, two different offsets to choose from: the offset from before
/// the transition and the offset from after the transition.
///
/// The purpose of this type is to represent that ambiguity (when it occurs)
/// and enable callers to make a choice about how to resolve that ambiguity.
/// In some cases, you might want to reject ambiguity altogether, which is
/// supported by the [`AmbiguousTimestamp::unambiguous`] routine.
///
/// This type provides four different out-of-the-box disambiguation strategies:
///
/// * [`AmbiguousTimestamp::compatible`] implements the
/// [`Disambiguation::Compatible`] strategy. In the case of a gap, the offset
/// after the gap is selected. In the case of a fold, the offset before the
/// fold occurs is selected.
/// * [`AmbiguousTimestamp::earlier`] implements the
/// [`Disambiguation::Earlier`] strategy. This always selects the "earlier"
/// offset.
/// * [`AmbiguousTimestamp::later`] implements the
/// [`Disambiguation::Later`] strategy. This always selects the "later"
/// offset.
/// * [`AmbiguousTimestamp::unambiguous`] implements the
/// [`Disambiguation::Reject`] strategy. It acts as an assertion that the
/// offset is unambiguous. If it is ambiguous, then an appropriate error is
/// returned.
///
/// The [`AmbiguousTimestamp::disambiguate`] method can be used with the
/// [`Disambiguation`] enum when the disambiguation strategy isn't known until
/// runtime.
///
/// Note also that these aren't the only disambiguation strategies. The
/// [`AmbiguousOffset`] type, accessible via [`AmbiguousTimestamp::offset`],
/// exposes the full details of the ambiguity. So any strategy can be
/// implemented.
///
/// # Example
///
/// This example shows how the "compatible" disambiguation strategy is
/// implemented. Recall that the "compatible" strategy chooses the offset
/// corresponding to the civil datetime after a gap, and the offset
/// corresponding to the civil datetime before a gap.
///
/// ```
/// use jiff::{civil::date, tz::{self, AmbiguousOffset}};
///
/// let tz = tz::db().get("America/New_York")?;
/// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
/// let offset = match tz.to_ambiguous_timestamp(dt).offset() {
/// AmbiguousOffset::Unambiguous { offset } => offset,
/// // This is counter-intuitive, but in order to get the civil datetime
/// // *after* the gap, we need to select the offset from *before* the
/// // gap.
/// AmbiguousOffset::Gap { before, .. } => before,
/// AmbiguousOffset::Fold { before, .. } => before,
/// };
/// assert_eq!(offset.to_timestamp(dt)?.to_string(), "2024-03-10T07:30:00Z");
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AmbiguousTimestamp {
dt: DateTime,
offset: AmbiguousOffset,
}
impl AmbiguousTimestamp {
#[inline]
fn new(dt: DateTime, kind: AmbiguousOffset) -> AmbiguousTimestamp {
AmbiguousTimestamp { dt, offset: kind }
}
/// Returns the civil datetime that was used to create this ambiguous
/// timestamp.
///
/// # Example
///
/// ```
/// use jiff::{civil::date, tz};
///
/// let tz = tz::db().get("America/New_York")?;
/// let dt = date(2024, 7, 10).at(17, 15, 0, 0);
/// let ts = tz.to_ambiguous_timestamp(dt);
/// assert_eq!(ts.datetime(), dt);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn datetime(&self) -> DateTime {
self.dt
}
/// Returns the possibly ambiguous offset that is the ultimate source of
/// ambiguity.
///
/// Most civil datetimes are not ambiguous, and thus, the offset will not
/// be ambiguous either. In this case, the offset returned will be the
/// [`AmbiguousOffset::Unambiguous`] variant.
///
/// But, not all civil datetimes are unambiguous. There are exactly two
/// cases where a civil datetime can be ambiguous: when a civil datetime
/// does not exist (a gap) or when a civil datetime is repeated (a fold).
/// In both such cases, the _offset_ is the thing that is ambiguous as
/// there are two possible choices for the offset in both cases: the offset
/// before the transition (whether it's a gap or a fold) or the offset
/// after the transition.
///
/// This type captures the fact that computing an offset from a civil
/// datetime in a particular time zone is in one of three possible states:
///
/// 1. It is unambiguous.
/// 2. It is ambiguous because there is a gap in time.
/// 3. It is ambiguous because there is a fold in time.
///
/// # Example
///
/// ```
/// use jiff::{civil::date, tz::{self, AmbiguousOffset}};
///
/// let tz = tz::db().get("America/New_York")?;
///
/// // Not ambiguous.
/// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
/// let ts = tz.to_ambiguous_timestamp(dt);
/// assert_eq!(ts.offset(), AmbiguousOffset::Unambiguous {
/// offset: tz::offset(-4),
/// });
///
/// // Ambiguous because of a gap.
/// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
/// let ts = tz.to_ambiguous_timestamp(dt);
/// assert_eq!(ts.offset(), AmbiguousOffset::Gap {
/// before: tz::offset(-5),
/// after: tz::offset(-4),
/// });
///
/// // Ambiguous because of a fold.
/// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
/// let ts = tz.to_ambiguous_timestamp(dt);
/// assert_eq!(ts.offset(), AmbiguousOffset::Fold {
/// before: tz::offset(-4),
/// after: tz::offset(-5),
/// });
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn offset(&self) -> AmbiguousOffset {
self.offset
}
/// Returns true if and only if this possibly ambiguous timestamp is
/// actually ambiguous.
///
/// This occurs precisely in cases when the offset is _not_
/// [`AmbiguousOffset::Unambiguous`].
///
/// # Example
///
/// ```
/// use jiff::{civil::date, tz::{self, AmbiguousOffset}};
///
/// let tz = tz::db().get("America/New_York")?;
///
/// // Not ambiguous.
/// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
/// let ts = tz.to_ambiguous_timestamp(dt);
/// assert!(!ts.is_ambiguous());
///
/// // Ambiguous because of a gap.
/// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
/// let ts = tz.to_ambiguous_timestamp(dt);
/// assert!(ts.is_ambiguous());
///
/// // Ambiguous because of a fold.
/// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
/// let ts = tz.to_ambiguous_timestamp(dt);
/// assert!(ts.is_ambiguous());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn is_ambiguous(&self) -> bool {
!matches!(self.offset(), AmbiguousOffset::Unambiguous { .. })
}
/// Disambiguates this timestamp according to the
/// [`Disambiguation::Compatible`] strategy.
///
/// If this timestamp is unambiguous, then this is a no-op.
///
/// The "compatible" strategy selects the offset corresponding to the civil
/// time after a gap, and the offset corresponding to the civil time before
/// a fold. This is what is specified in [RFC 5545].
///
/// [RFC 5545]: https://datatracker.ietf.org/doc/html/rfc5545
///
/// # Errors
///
/// This returns an error when the combination of the civil datetime
/// and offset would lead to a `Timestamp` outside of the
/// [`Timestamp::MIN`] and [`Timestamp::MAX`] limits. This only occurs
/// when the civil datetime is "close" to its own [`DateTime::MIN`]
/// and [`DateTime::MAX`] limits.
///
/// # Example
///
/// ```
/// use jiff::{civil::date, tz};
///
/// let tz = tz::db().get("America/New_York")?;
///
/// // Not ambiguous.
/// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
/// let ts = tz.to_ambiguous_timestamp(dt);
/// assert_eq!(
/// ts.compatible()?.to_string(),
/// "2024-07-15T21:30:00Z",
/// );
///
/// // Ambiguous because of a gap.
/// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
/// let ts = tz.to_ambiguous_timestamp(dt);
/// assert_eq!(
/// ts.compatible()?.to_string(),
/// "2024-03-10T07:30:00Z",
/// );
///
/// // Ambiguous because of a fold.
/// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
/// let ts = tz.to_ambiguous_timestamp(dt);
/// assert_eq!(
/// ts.compatible()?.to_string(),
/// "2024-11-03T05:30:00Z",
/// );
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn compatible(self) -> Result<Timestamp, Error> {
let offset = match self.offset() {
AmbiguousOffset::Unambiguous { offset } => offset,
AmbiguousOffset::Gap { before, .. } => before,
AmbiguousOffset::Fold { before, .. } => before,
};
offset.to_timestamp(self.dt)
}
/// Disambiguates this timestamp according to the
/// [`Disambiguation::Earlier`] strategy.
///
/// If this timestamp is unambiguous, then this is a no-op.
///
/// The "earlier" strategy selects the offset corresponding to the civil
/// time before a gap, and the offset corresponding to the civil time
/// before a fold.
///
/// # Errors
///
/// This returns an error when the combination of the civil datetime
/// and offset would lead to a `Timestamp` outside of the
/// [`Timestamp::MIN`] and [`Timestamp::MAX`] limits. This only occurs
/// when the civil datetime is "close" to its own [`DateTime::MIN`]
/// and [`DateTime::MAX`] limits.
///
/// # Example
///
/// ```
/// use jiff::{civil::date, tz};
///
/// let tz = tz::db().get("America/New_York")?;
///
/// // Not ambiguous.
/// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
/// let ts = tz.to_ambiguous_timestamp(dt);
/// assert_eq!(
/// ts.earlier()?.to_string(),
/// "2024-07-15T21:30:00Z",
/// );
///
/// // Ambiguous because of a gap.
/// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
/// let ts = tz.to_ambiguous_timestamp(dt);
/// assert_eq!(
/// ts.earlier()?.to_string(),
/// "2024-03-10T06:30:00Z",
/// );
///
/// // Ambiguous because of a fold.
/// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
/// let ts = tz.to_ambiguous_timestamp(dt);
/// assert_eq!(
/// ts.earlier()?.to_string(),
/// "2024-11-03T05:30:00Z",
/// );
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn earlier(self) -> Result<Timestamp, Error> {
let offset = match self.offset() {
AmbiguousOffset::Unambiguous { offset } => offset,
AmbiguousOffset::Gap { after, .. } => after,
AmbiguousOffset::Fold { before, .. } => before,
};
offset.to_timestamp(self.dt)
}
/// Disambiguates this timestamp according to the
/// [`Disambiguation::Later`] strategy.
///
/// If this timestamp is unambiguous, then this is a no-op.
///
/// The "later" strategy selects the offset corresponding to the civil
/// time after a gap, and the offset corresponding to the civil time
/// after a fold.
///
/// # Errors
///
/// This returns an error when the combination of the civil datetime
/// and offset would lead to a `Timestamp` outside of the
/// [`Timestamp::MIN`] and [`Timestamp::MAX`] limits. This only occurs
/// when the civil datetime is "close" to its own [`DateTime::MIN`]
/// and [`DateTime::MAX`] limits.
///
/// # Example
///
/// ```
/// use jiff::{civil::date, tz};
///
/// let tz = tz::db().get("America/New_York")?;
///
/// // Not ambiguous.
/// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
/// let ts = tz.to_ambiguous_timestamp(dt);
/// assert_eq!(
/// ts.later()?.to_string(),
/// "2024-07-15T21:30:00Z",
/// );
///
/// // Ambiguous because of a gap.
/// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
/// let ts = tz.to_ambiguous_timestamp(dt);
/// assert_eq!(
/// ts.later()?.to_string(),
/// "2024-03-10T07:30:00Z",
/// );
///
/// // Ambiguous because of a fold.
/// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
/// let ts = tz.to_ambiguous_timestamp(dt);
/// assert_eq!(
/// ts.later()?.to_string(),
/// "2024-11-03T06:30:00Z",
/// );
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn later(self) -> Result<Timestamp, Error> {
let offset = match self.offset() {
AmbiguousOffset::Unambiguous { offset } => offset,
AmbiguousOffset::Gap { before, .. } => before,
AmbiguousOffset::Fold { after, .. } => after,
};
offset.to_timestamp(self.dt)
}
/// Disambiguates this timestamp according to the
/// [`Disambiguation::Reject`] strategy.
///
/// If this timestamp is unambiguous, then this is a no-op.
///
/// The "reject" strategy always returns an error when the timestamp
/// is ambiguous.
///
/// # Errors
///
/// This returns an error when the combination of the civil datetime
/// and offset would lead to a `Timestamp` outside of the
/// [`Timestamp::MIN`] and [`Timestamp::MAX`] limits. This only occurs
/// when the civil datetime is "close" to its own [`DateTime::MIN`]
/// and [`DateTime::MAX`] limits.
///
/// This also returns an error when the timestamp is ambiguous.
///
/// # Example
///
/// ```
/// use jiff::{civil::date, tz};
///
/// let tz = tz::db().get("America/New_York")?;
///
/// // Not ambiguous.
/// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
/// let ts = tz.to_ambiguous_timestamp(dt);
/// assert_eq!(
/// ts.later()?.to_string(),
/// "2024-07-15T21:30:00Z",
/// );
///
/// // Ambiguous because of a gap.
/// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
/// let ts = tz.to_ambiguous_timestamp(dt);
/// assert!(ts.unambiguous().is_err());
///
/// // Ambiguous because of a fold.
/// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
/// let ts = tz.to_ambiguous_timestamp(dt);
/// assert!(ts.unambiguous().is_err());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn unambiguous(self) -> Result<Timestamp, Error> {
let offset = match self.offset() {
AmbiguousOffset::Unambiguous { offset } => offset,
AmbiguousOffset::Gap { before, after } => {
return Err(err!(
"the datetime {dt} is ambiguous since it falls into \
a gap between offsets {before} and {after}",
dt = self.dt,
));
}
AmbiguousOffset::Fold { before, after } => {
return Err(err!(
"the datetime {dt} is ambiguous since it falls into \
a fold between offsets {before} and {after}",
dt = self.dt,
));
}
};
offset.to_timestamp(self.dt)
}
/// Disambiguates this (possibly ambiguous) timestamp into a specific
/// timestamp.
///
/// This is the same as calling one of the disambiguation methods, but
/// the method chosen is indicated by the option given. This is useful
/// when the disambiguation option needs to be chosen at runtime.
///
/// # Errors
///
/// This returns an error if this would have returned a timestamp
/// outside of its minimum and maximum values.
///
/// This can also return an error when using the [`Disambiguation::Reject`]
/// strategy. Namely, when using the `Reject` strategy, any ambiguous
/// timestamp always results in an error.
///
/// # Example
///
/// This example shows the various disambiguation modes when given a
/// datetime that falls in a "fold" (i.e., a backwards DST transition).
///
/// ```
/// use jiff::{civil::date, tz::{self, Disambiguation}};
///
/// let newyork = tz::db().get("America/New_York")?;
/// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
/// let ambiguous = newyork.to_ambiguous_timestamp(dt);
///
/// // In compatible mode, backward transitions select the earlier
/// // time. In the EDT->EST transition, that's the -04 (EDT) offset.
/// let ts = ambiguous.clone().disambiguate(Disambiguation::Compatible)?;
/// assert_eq!(ts.to_string(), "2024-11-03T05:30:00Z");
///
/// // The earlier time in the EDT->EST transition is the -04 (EDT) offset.
/// let ts = ambiguous.clone().disambiguate(Disambiguation::Earlier)?;
/// assert_eq!(ts.to_string(), "2024-11-03T05:30:00Z");
///
/// // The later time in the EDT->EST transition is the -05 (EST) offset.
/// let ts = ambiguous.clone().disambiguate(Disambiguation::Later)?;
/// assert_eq!(ts.to_string(), "2024-11-03T06:30:00Z");
///
/// // Since our datetime is ambiguous, the 'reject' strategy errors.
/// assert!(ambiguous.disambiguate(Disambiguation::Reject).is_err());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn disambiguate(
self,
option: Disambiguation,
) -> Result<Timestamp, Error> {
match option {
Disambiguation::Compatible => self.compatible(),
Disambiguation::Earlier => self.earlier(),
Disambiguation::Later => self.later(),
Disambiguation::Reject => self.unambiguous(),
}
}
/// Convert this ambiguous timestamp into an ambiguous zoned date time by
/// attaching a time zone.
///
/// This is useful when you have a [`civil::DateTime`], [`TimeZone`] and
/// want to convert it to an instant while applying a particular
/// disambiguation strategy without an extra clone of the `TimeZone`.
///
/// This isn't currently exposed because I believe use cases for crate
/// users can be satisfied via [`TimeZone::into_ambiguous_zoned`] (which
/// is implemented via this routine).
#[inline]
fn into_ambiguous_zoned(self, tz: TimeZone) -> AmbiguousZoned {
AmbiguousZoned::new(self, tz)
}
}
/// A possibly ambiguous [`Zoned`], created by
/// [`TimeZone::to_ambiguous_zoned`].
///
/// While this is called an ambiguous zoned datetime, the thing that is
/// actually ambiguous is the offset. That is, an ambiguous zoned datetime
/// is actually a triple of a [`civil::DateTime`](crate::civil::DateTime), a
/// [`TimeZone`] and an [`AmbiguousOffset`].
///
/// When the offset is ambiguous, it either represents a gap (civil time is
/// skipped) or a fold (civil time is repeated). In both cases, there are, by
/// construction, two different offsets to choose from: the offset from before
/// the transition and the offset from after the transition.
///
/// The purpose of this type is to represent that ambiguity (when it occurs)
/// and enable callers to make a choice about how to resolve that ambiguity.
/// In some cases, you might want to reject ambiguity altogether, which is
/// supported by the [`AmbiguousZoned::unambiguous`] routine.
///
/// This type provides four different out-of-the-box disambiguation strategies:
///
/// * [`AmbiguousZoned::compatible`] implements the
/// [`Disambiguation::Compatible`] strategy. In the case of a gap, the offset
/// after the gap is selected. In the case of a fold, the offset before the
/// fold occurs is selected.
/// * [`AmbiguousZoned::earlier`] implements the
/// [`Disambiguation::Earlier`] strategy. This always selects the "earlier"
/// offset.
/// * [`AmbiguousZoned::later`] implements the
/// [`Disambiguation::Later`] strategy. This always selects the "later"
/// offset.
/// * [`AmbiguousZoned::unambiguous`] implements the
/// [`Disambiguation::Reject`] strategy. It acts as an assertion that the
/// offset is unambiguous. If it is ambiguous, then an appropriate error is
/// returned.
///
/// The [`AmbiguousZoned::disambiguate`] method can be used with the
/// [`Disambiguation`] enum when the disambiguation strategy isn't known until
/// runtime.
///
/// Note also that these aren't the only disambiguation strategies. The
/// [`AmbiguousOffset`] type, accessible via [`AmbiguousZoned::offset`],
/// exposes the full details of the ambiguity. So any strategy can be
/// implemented.
///
/// # Example
///
/// This example shows how the "compatible" disambiguation strategy is
/// implemented. Recall that the "compatible" strategy chooses the offset
/// corresponding to the civil datetime after a gap, and the offset
/// corresponding to the civil datetime before a gap.
///
/// ```
/// use jiff::{civil::date, tz::{self, AmbiguousOffset}};
///
/// let tz = tz::db().get("America/New_York")?;
/// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
/// let ambiguous = tz.to_ambiguous_zoned(dt);
/// let offset = match ambiguous.offset() {
/// AmbiguousOffset::Unambiguous { offset } => offset,
/// // This is counter-intuitive, but in order to get the civil datetime
/// // *after* the gap, we need to select the offset from *before* the
/// // gap.
/// AmbiguousOffset::Gap { before, .. } => before,
/// AmbiguousOffset::Fold { before, .. } => before,
/// };
/// let zdt = offset.to_timestamp(dt)?.to_zoned(ambiguous.into_time_zone());
/// assert_eq!(zdt.to_string(), "2024-03-10T03:30:00-04:00[America/New_York]");
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AmbiguousZoned {
ts: AmbiguousTimestamp,
tz: TimeZone,
}
impl AmbiguousZoned {
#[inline]
fn new(ts: AmbiguousTimestamp, tz: TimeZone) -> AmbiguousZoned {
AmbiguousZoned { ts, tz }
}
/// Returns a reference to the time zone that was used to create this
/// ambiguous zoned datetime.
///
/// # Example
///
/// ```
/// use jiff::{civil::date, tz};
///
/// let tz = tz::db().get("America/New_York")?;
/// let dt = date(2024, 7, 10).at(17, 15, 0, 0);
/// let zdt = tz.to_ambiguous_zoned(dt);
/// assert_eq!(&tz, zdt.time_zone());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn time_zone(&self) -> &TimeZone {
&self.tz
}
/// Consumes this ambiguous zoned datetime and returns the underlying
/// `TimeZone`. This is useful if you no longer need the ambiguous zoned
/// datetime and want its `TimeZone` without cloning it. (Cloning a
/// `TimeZone` is cheap but not free.)
///
/// # Example
///
/// ```
/// use jiff::{civil::date, tz};
///
/// let tz = tz::db().get("America/New_York")?;
/// let dt = date(2024, 7, 10).at(17, 15, 0, 0);
/// let zdt = tz.to_ambiguous_zoned(dt);
/// assert_eq!(tz, zdt.into_time_zone());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn into_time_zone(self) -> TimeZone {
self.tz
}
/// Returns the civil datetime that was used to create this ambiguous
/// zoned datetime.
///
/// # Example
///
/// ```
/// use jiff::{civil::date, tz};
///
/// let tz = tz::db().get("America/New_York")?;
/// let dt = date(2024, 7, 10).at(17, 15, 0, 0);
/// let zdt = tz.to_ambiguous_zoned(dt);
/// assert_eq!(zdt.datetime(), dt);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn datetime(&self) -> DateTime {
self.ts.datetime()
}
/// Returns the possibly ambiguous offset that is the ultimate source of
/// ambiguity.
///
/// Most civil datetimes are not ambiguous, and thus, the offset will not
/// be ambiguous either. In this case, the offset returned will be the
/// [`AmbiguousOffset::Unambiguous`] variant.
///
/// But, not all civil datetimes are unambiguous. There are exactly two
/// cases where a civil datetime can be ambiguous: when a civil datetime
/// does not exist (a gap) or when a civil datetime is repeated (a fold).
/// In both such cases, the _offset_ is the thing that is ambiguous as
/// there are two possible choices for the offset in both cases: the offset
/// before the transition (whether it's a gap or a fold) or the offset
/// after the transition.
///
/// This type captures the fact that computing an offset from a civil
/// datetime in a particular time zone is in one of three possible states:
///
/// 1. It is unambiguous.
/// 2. It is ambiguous because there is a gap in time.
/// 3. It is ambiguous because there is a fold in time.
///
/// # Example
///
/// ```
/// use jiff::{civil::date, tz::{self, AmbiguousOffset}};
///
/// let tz = tz::db().get("America/New_York")?;
///
/// // Not ambiguous.
/// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
/// let zdt = tz.to_ambiguous_zoned(dt);
/// assert_eq!(zdt.offset(), AmbiguousOffset::Unambiguous {
/// offset: tz::offset(-4),
/// });
///
/// // Ambiguous because of a gap.
/// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
/// let zdt = tz.to_ambiguous_zoned(dt);
/// assert_eq!(zdt.offset(), AmbiguousOffset::Gap {
/// before: tz::offset(-5),
/// after: tz::offset(-4),
/// });
///
/// // Ambiguous because of a fold.
/// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
/// let zdt = tz.to_ambiguous_zoned(dt);
/// assert_eq!(zdt.offset(), AmbiguousOffset::Fold {
/// before: tz::offset(-4),
/// after: tz::offset(-5),
/// });
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn offset(&self) -> AmbiguousOffset {
self.ts.offset
}
/// Returns true if and only if this possibly ambiguous zoned datetime is
/// actually ambiguous.
///
/// This occurs precisely in cases when the offset is _not_
/// [`AmbiguousOffset::Unambiguous`].
///
/// # Example
///
/// ```
/// use jiff::{civil::date, tz::{self, AmbiguousOffset}};
///
/// let tz = tz::db().get("America/New_York")?;
///
/// // Not ambiguous.
/// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
/// let zdt = tz.to_ambiguous_zoned(dt);
/// assert!(!zdt.is_ambiguous());
///
/// // Ambiguous because of a gap.
/// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
/// let zdt = tz.to_ambiguous_zoned(dt);
/// assert!(zdt.is_ambiguous());
///
/// // Ambiguous because of a fold.
/// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
/// let zdt = tz.to_ambiguous_zoned(dt);
/// assert!(zdt.is_ambiguous());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn is_ambiguous(&self) -> bool {
!matches!(self.offset(), AmbiguousOffset::Unambiguous { .. })
}
/// Disambiguates this zoned datetime according to the
/// [`Disambiguation::Compatible`] strategy.
///
/// If this zoned datetime is unambiguous, then this is a no-op.
///
/// The "compatible" strategy selects the offset corresponding to the civil
/// time after a gap, and the offset corresponding to the civil time before
/// a fold. This is what is specified in [RFC 5545].
///
/// [RFC 5545]: https://datatracker.ietf.org/doc/html/rfc5545
///
/// # Errors
///
/// This returns an error when the combination of the civil datetime
/// and offset would lead to a `Zoned` with a timestamp outside of the
/// [`Timestamp::MIN`] and [`Timestamp::MAX`] limits. This only occurs
/// when the civil datetime is "close" to its own [`DateTime::MIN`]
/// and [`DateTime::MAX`] limits.
///
/// # Example
///
/// ```
/// use jiff::{civil::date, tz};
///
/// let tz = tz::db().get("America/New_York")?;
///
/// // Not ambiguous.
/// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
/// let zdt = tz.to_ambiguous_zoned(dt);
/// assert_eq!(
/// zdt.compatible()?.to_string(),
/// "2024-07-15T17:30:00-04:00[America/New_York]",
/// );
///
/// // Ambiguous because of a gap.
/// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
/// let zdt = tz.to_ambiguous_zoned(dt);
/// assert_eq!(
/// zdt.compatible()?.to_string(),
/// "2024-03-10T03:30:00-04:00[America/New_York]",
/// );
///
/// // Ambiguous because of a fold.
/// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
/// let zdt = tz.to_ambiguous_zoned(dt);
/// assert_eq!(
/// zdt.compatible()?.to_string(),
/// "2024-11-03T01:30:00-04:00[America/New_York]",
/// );
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn compatible(self) -> Result<Zoned, Error> {
let ts = self.ts.compatible().with_context(|| {
err!(
"error converting datetime {dt} to instant in time zone {tz}",
dt = self.datetime(),
tz = self.time_zone().diagnostic_name(),
)
})?;
Ok(ts.to_zoned(self.tz))
}
/// Disambiguates this zoned datetime according to the
/// [`Disambiguation::Earlier`] strategy.
///
/// If this zoned datetime is unambiguous, then this is a no-op.
///
/// The "earlier" strategy selects the offset corresponding to the civil
/// time before a gap, and the offset corresponding to the civil time
/// before a fold.
///
/// # Errors
///
/// This returns an error when the combination of the civil datetime
/// and offset would lead to a `Zoned` with a timestamp outside of the
/// [`Timestamp::MIN`] and [`Timestamp::MAX`] limits. This only occurs
/// when the civil datetime is "close" to its own [`DateTime::MIN`]
/// and [`DateTime::MAX`] limits.
///
/// # Example
///
/// ```
/// use jiff::{civil::date, tz};
///
/// let tz = tz::db().get("America/New_York")?;
///
/// // Not ambiguous.
/// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
/// let zdt = tz.to_ambiguous_zoned(dt);
/// assert_eq!(
/// zdt.earlier()?.to_string(),
/// "2024-07-15T17:30:00-04:00[America/New_York]",
/// );
///
/// // Ambiguous because of a gap.
/// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
/// let zdt = tz.to_ambiguous_zoned(dt);
/// assert_eq!(
/// zdt.earlier()?.to_string(),
/// "2024-03-10T01:30:00-05:00[America/New_York]",
/// );
///
/// // Ambiguous because of a fold.
/// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
/// let zdt = tz.to_ambiguous_zoned(dt);
/// assert_eq!(
/// zdt.earlier()?.to_string(),
/// "2024-11-03T01:30:00-04:00[America/New_York]",
/// );
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn earlier(self) -> Result<Zoned, Error> {
let ts = self.ts.earlier().with_context(|| {
err!(
"error converting datetime {dt} to instant in time zone {tz}",
dt = self.datetime(),
tz = self.time_zone().diagnostic_name(),
)
})?;
Ok(ts.to_zoned(self.tz))
}
/// Disambiguates this zoned datetime according to the
/// [`Disambiguation::Later`] strategy.
///
/// If this zoned datetime is unambiguous, then this is a no-op.
///
/// The "later" strategy selects the offset corresponding to the civil
/// time after a gap, and the offset corresponding to the civil time
/// after a fold.
///
/// # Errors
///
/// This returns an error when the combination of the civil datetime
/// and offset would lead to a `Zoned` with a timestamp outside of the
/// [`Timestamp::MIN`] and [`Timestamp::MAX`] limits. This only occurs
/// when the civil datetime is "close" to its own [`DateTime::MIN`]
/// and [`DateTime::MAX`] limits.
///
/// # Example
///
/// ```
/// use jiff::{civil::date, tz};
///
/// let tz = tz::db().get("America/New_York")?;
///
/// // Not ambiguous.
/// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
/// let zdt = tz.to_ambiguous_zoned(dt);
/// assert_eq!(
/// zdt.later()?.to_string(),
/// "2024-07-15T17:30:00-04:00[America/New_York]",
/// );
///
/// // Ambiguous because of a gap.
/// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
/// let zdt = tz.to_ambiguous_zoned(dt);
/// assert_eq!(
/// zdt.later()?.to_string(),
/// "2024-03-10T03:30:00-04:00[America/New_York]",
/// );
///
/// // Ambiguous because of a fold.
/// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
/// let zdt = tz.to_ambiguous_zoned(dt);
/// assert_eq!(
/// zdt.later()?.to_string(),
/// "2024-11-03T01:30:00-05:00[America/New_York]",
/// );
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn later(self) -> Result<Zoned, Error> {
let ts = self.ts.later().with_context(|| {
err!(
"error converting datetime {dt} to instant in time zone {tz}",
dt = self.datetime(),
tz = self.time_zone().diagnostic_name(),
)
})?;
Ok(ts.to_zoned(self.tz))
}
/// Disambiguates this zoned datetime according to the
/// [`Disambiguation::Reject`] strategy.
///
/// If this zoned datetime is unambiguous, then this is a no-op.
///
/// The "reject" strategy always returns an error when the zoned datetime
/// is ambiguous.
///
/// # Errors
///
/// This returns an error when the combination of the civil datetime
/// and offset would lead to a `Zoned` with a timestamp outside of the
/// [`Timestamp::MIN`] and [`Timestamp::MAX`] limits. This only occurs
/// when the civil datetime is "close" to its own [`DateTime::MIN`]
/// and [`DateTime::MAX`] limits.
///
/// This also returns an error when the timestamp is ambiguous.
///
/// # Example
///
/// ```
/// use jiff::{civil::date, tz};
///
/// let tz = tz::db().get("America/New_York")?;
///
/// // Not ambiguous.
/// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
/// let zdt = tz.to_ambiguous_zoned(dt);
/// assert_eq!(
/// zdt.later()?.to_string(),
/// "2024-07-15T17:30:00-04:00[America/New_York]",
/// );
///
/// // Ambiguous because of a gap.
/// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
/// let zdt = tz.to_ambiguous_zoned(dt);
/// assert!(zdt.unambiguous().is_err());
///
/// // Ambiguous because of a fold.
/// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
/// let zdt = tz.to_ambiguous_zoned(dt);
/// assert!(zdt.unambiguous().is_err());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn unambiguous(self) -> Result<Zoned, Error> {
let ts = self.ts.unambiguous().with_context(|| {
err!(
"error converting datetime {dt} to instant in time zone {tz}",
dt = self.datetime(),
tz = self.time_zone().diagnostic_name(),
)
})?;
Ok(ts.to_zoned(self.tz))
}
/// Disambiguates this (possibly ambiguous) timestamp into a concrete
/// time zone aware timestamp.
///
/// This is the same as calling one of the disambiguation methods, but
/// the method chosen is indicated by the option given. This is useful
/// when the disambiguation option needs to be chosen at runtime.
///
/// # Errors
///
/// This returns an error if this would have returned a zoned datetime
/// outside of its minimum and maximum values.
///
/// This can also return an error when using the [`Disambiguation::Reject`]
/// strategy. Namely, when using the `Reject` strategy, any ambiguous
/// timestamp always results in an error.
///
/// # Example
///
/// This example shows the various disambiguation modes when given a
/// datetime that falls in a "fold" (i.e., a backwards DST transition).
///
/// ```
/// use jiff::{civil::date, tz::{self, Disambiguation}};
///
/// let newyork = tz::db().get("America/New_York")?;
/// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
/// let ambiguous = newyork.to_ambiguous_zoned(dt);
///
/// // In compatible mode, backward transitions select the earlier
/// // time. In the EDT->EST transition, that's the -04 (EDT) offset.
/// let zdt = ambiguous.clone().disambiguate(Disambiguation::Compatible)?;
/// assert_eq!(
/// zdt.to_string(),
/// "2024-11-03T01:30:00-04:00[America/New_York]",
/// );
///
/// // The earlier time in the EDT->EST transition is the -04 (EDT) offset.
/// let zdt = ambiguous.clone().disambiguate(Disambiguation::Earlier)?;
/// assert_eq!(
/// zdt.to_string(),
/// "2024-11-03T01:30:00-04:00[America/New_York]",
/// );
///
/// // The later time in the EDT->EST transition is the -05 (EST) offset.
/// let zdt = ambiguous.clone().disambiguate(Disambiguation::Later)?;
/// assert_eq!(
/// zdt.to_string(),
/// "2024-11-03T01:30:00-05:00[America/New_York]",
/// );
///
/// // Since our datetime is ambiguous, the 'reject' strategy errors.
/// assert!(ambiguous.disambiguate(Disambiguation::Reject).is_err());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn disambiguate(self, option: Disambiguation) -> Result<Zoned, Error> {
match option {
Disambiguation::Compatible => self.compatible(),
Disambiguation::Earlier => self.earlier(),
Disambiguation::Later => self.later(),
Disambiguation::Reject => self.unambiguous(),
}
}
}
/// Creates a new time zone offset in a `const` context from a given number
/// of hours.
///
/// Negative offsets correspond to time zones west of the prime meridian,
/// while positive offsets correspond to time zones east of the prime
/// meridian. Equivalently, in all cases, `civil-time - offset = UTC`.
///
/// The fallible non-const version of this constructor is
/// [`Offset::from_hours`].
///
/// This is a convenience free function for [`Offset::constant`]. It is
/// intended to provide a terse syntax for constructing `Offset` values from
/// a value that is known to be valid.
///
/// # Panics
///
/// This routine panics when the given number of hours is out of range.
/// Namely, `hours` must be in the range `-25..=25`.
///
/// Similarly, when used in a const context, an out of bounds hour will prevent
/// your Rust program from compiling.
///
/// # Example
///
/// ```
/// use jiff::tz::offset;
///
/// let o = offset(-5);
/// assert_eq!(o.seconds(), -18_000);
/// let o = offset(5);
/// assert_eq!(o.seconds(), 18_000);
/// ```
#[inline]
pub const fn offset(hours: i8) -> Offset {
Offset::constant(hours)
}
#[cfg(test)]
mod tests {
use crate::{civil::date, tz::testdata::TzifTestFile};
use super::*;
fn unambiguous(offset_hours: i8) -> AmbiguousOffset {
let offset = offset(offset_hours);
o_unambiguous(offset)
}
fn gap(
earlier_offset_hours: i8,
later_offset_hours: i8,
) -> AmbiguousOffset {
let earlier = offset(earlier_offset_hours);
let later = offset(later_offset_hours);
o_gap(earlier, later)
}
fn fold(
earlier_offset_hours: i8,
later_offset_hours: i8,
) -> AmbiguousOffset {
let earlier = offset(earlier_offset_hours);
let later = offset(later_offset_hours);
o_fold(earlier, later)
}
fn o_unambiguous(offset: Offset) -> AmbiguousOffset {
AmbiguousOffset::Unambiguous { offset }
}
fn o_gap(earlier: Offset, later: Offset) -> AmbiguousOffset {
AmbiguousOffset::Gap { before: earlier, after: later }
}
fn o_fold(earlier: Offset, later: Offset) -> AmbiguousOffset {
AmbiguousOffset::Fold { before: earlier, after: later }
}
#[test]
fn time_zone_tzif_to_ambiguous_timestamp() {
let tests: &[(&str, &[_])] = &[
(
"America/New_York",
&[
((1969, 12, 31, 19, 0, 0, 0), unambiguous(-5)),
((2024, 3, 10, 1, 59, 59, 999_999_999), unambiguous(-5)),
((2024, 3, 10, 2, 0, 0, 0), gap(-5, -4)),
((2024, 3, 10, 2, 59, 59, 999_999_999), gap(-5, -4)),
((2024, 3, 10, 3, 0, 0, 0), unambiguous(-4)),
((2024, 11, 3, 0, 59, 59, 999_999_999), unambiguous(-4)),
((2024, 11, 3, 1, 0, 0, 0), fold(-4, -5)),
((2024, 11, 3, 1, 59, 59, 999_999_999), fold(-4, -5)),
((2024, 11, 3, 2, 0, 0, 0), unambiguous(-5)),
],
),
(
"Europe/Dublin",
&[
((1970, 1, 1, 0, 0, 0, 0), unambiguous(1)),
((2024, 3, 31, 0, 59, 59, 999_999_999), unambiguous(0)),
((2024, 3, 31, 1, 0, 0, 0), gap(0, 1)),
((2024, 3, 31, 1, 59, 59, 999_999_999), gap(0, 1)),
((2024, 3, 31, 2, 0, 0, 0), unambiguous(1)),
((2024, 10, 27, 0, 59, 59, 999_999_999), unambiguous(1)),
((2024, 10, 27, 1, 0, 0, 0), fold(1, 0)),
((2024, 10, 27, 1, 59, 59, 999_999_999), fold(1, 0)),
((2024, 10, 27, 2, 0, 0, 0), unambiguous(0)),
],
),
(
"Australia/Tasmania",
&[
((1970, 1, 1, 11, 0, 0, 0), unambiguous(11)),
((2024, 4, 7, 1, 59, 59, 999_999_999), unambiguous(11)),
((2024, 4, 7, 2, 0, 0, 0), fold(11, 10)),
((2024, 4, 7, 2, 59, 59, 999_999_999), fold(11, 10)),
((2024, 4, 7, 3, 0, 0, 0), unambiguous(10)),
((2024, 10, 6, 1, 59, 59, 999_999_999), unambiguous(10)),
((2024, 10, 6, 2, 0, 0, 0), gap(10, 11)),
((2024, 10, 6, 2, 59, 59, 999_999_999), gap(10, 11)),
((2024, 10, 6, 3, 0, 0, 0), unambiguous(11)),
],
),
(
"Antarctica/Troll",
&[
((1970, 1, 1, 0, 0, 0, 0), unambiguous(0)),
// test the gap
((2024, 3, 31, 0, 59, 59, 999_999_999), unambiguous(0)),
((2024, 3, 31, 1, 0, 0, 0), gap(0, 2)),
((2024, 3, 31, 1, 59, 59, 999_999_999), gap(0, 2)),
// still in the gap!
((2024, 3, 31, 2, 0, 0, 0), gap(0, 2)),
((2024, 3, 31, 2, 59, 59, 999_999_999), gap(0, 2)),
// finally out
((2024, 3, 31, 3, 0, 0, 0), unambiguous(2)),
// test the fold
((2024, 10, 27, 0, 59, 59, 999_999_999), unambiguous(2)),
((2024, 10, 27, 1, 0, 0, 0), fold(2, 0)),
((2024, 10, 27, 1, 59, 59, 999_999_999), fold(2, 0)),
// still in the fold!
((2024, 10, 27, 2, 0, 0, 0), fold(2, 0)),
((2024, 10, 27, 2, 59, 59, 999_999_999), fold(2, 0)),
// finally out
((2024, 10, 27, 3, 0, 0, 0), unambiguous(0)),
],
),
(
"America/St_Johns",
&[
(
(1969, 12, 31, 20, 30, 0, 0),
o_unambiguous(-Offset::hms(3, 30, 0)),
),
(
(2024, 3, 10, 1, 59, 59, 999_999_999),
o_unambiguous(-Offset::hms(3, 30, 0)),
),
(
(2024, 3, 10, 2, 0, 0, 0),
o_gap(-Offset::hms(3, 30, 0), -Offset::hms(2, 30, 0)),
),
(
(2024, 3, 10, 2, 59, 59, 999_999_999),
o_gap(-Offset::hms(3, 30, 0), -Offset::hms(2, 30, 0)),
),
(
(2024, 3, 10, 3, 0, 0, 0),
o_unambiguous(-Offset::hms(2, 30, 0)),
),
(
(2024, 11, 3, 0, 59, 59, 999_999_999),
o_unambiguous(-Offset::hms(2, 30, 0)),
),
(
(2024, 11, 3, 1, 0, 0, 0),
o_fold(-Offset::hms(2, 30, 0), -Offset::hms(3, 30, 0)),
),
(
(2024, 11, 3, 1, 59, 59, 999_999_999),
o_fold(-Offset::hms(2, 30, 0), -Offset::hms(3, 30, 0)),
),
(
(2024, 11, 3, 2, 0, 0, 0),
o_unambiguous(-Offset::hms(3, 30, 0)),
),
],
),
// This time zone has an interesting transition where it jumps
// backwards a full day at 1867-10-19T15:30:00.
(
"America/Sitka",
&[
((1969, 12, 31, 16, 0, 0, 0), unambiguous(-8)),
(
(-9999, 1, 2, 16, 58, 46, 0),
o_unambiguous(Offset::hms(14, 58, 47)),
),
(
(1867, 10, 18, 15, 29, 59, 0),
o_unambiguous(Offset::hms(14, 58, 47)),
),
(
(1867, 10, 18, 15, 30, 0, 0),
// A fold of 24 hours!!!
o_fold(
Offset::hms(14, 58, 47),
-Offset::hms(9, 1, 13),
),
),
(
(1867, 10, 19, 15, 29, 59, 999_999_999),
// Still in the fold...
o_fold(
Offset::hms(14, 58, 47),
-Offset::hms(9, 1, 13),
),
),
(
(1867, 10, 19, 15, 30, 0, 0),
// Finally out.
o_unambiguous(-Offset::hms(9, 1, 13)),
),
],
),
// As with to_datetime, we test every possible transition
// point here since this time zone has a small number of them.
(
"Pacific/Honolulu",
&[
(
(1896, 1, 13, 11, 59, 59, 0),
o_unambiguous(-Offset::hms(10, 31, 26)),
),
(
(1896, 1, 13, 12, 0, 0, 0),
o_gap(
-Offset::hms(10, 31, 26),
-Offset::hms(10, 30, 0),
),
),
(
(1896, 1, 13, 12, 1, 25, 0),
o_gap(
-Offset::hms(10, 31, 26),
-Offset::hms(10, 30, 0),
),
),
(
(1896, 1, 13, 12, 1, 26, 0),
o_unambiguous(-Offset::hms(10, 30, 0)),
),
(
(1933, 4, 30, 1, 59, 59, 0),
o_unambiguous(-Offset::hms(10, 30, 0)),
),
(
(1933, 4, 30, 2, 0, 0, 0),
o_gap(-Offset::hms(10, 30, 0), -Offset::hms(9, 30, 0)),
),
(
(1933, 4, 30, 2, 59, 59, 0),
o_gap(-Offset::hms(10, 30, 0), -Offset::hms(9, 30, 0)),
),
(
(1933, 4, 30, 3, 0, 0, 0),
o_unambiguous(-Offset::hms(9, 30, 0)),
),
(
(1933, 5, 21, 10, 59, 59, 0),
o_unambiguous(-Offset::hms(9, 30, 0)),
),
(
(1933, 5, 21, 11, 0, 0, 0),
o_fold(
-Offset::hms(9, 30, 0),
-Offset::hms(10, 30, 0),
),
),
(
(1933, 5, 21, 11, 59, 59, 0),
o_fold(
-Offset::hms(9, 30, 0),
-Offset::hms(10, 30, 0),
),
),
(
(1933, 5, 21, 12, 0, 0, 0),
o_unambiguous(-Offset::hms(10, 30, 0)),
),
(
(1942, 2, 9, 1, 59, 59, 0),
o_unambiguous(-Offset::hms(10, 30, 0)),
),
(
(1942, 2, 9, 2, 0, 0, 0),
o_gap(-Offset::hms(10, 30, 0), -Offset::hms(9, 30, 0)),
),
(
(1942, 2, 9, 2, 59, 59, 0),
o_gap(-Offset::hms(10, 30, 0), -Offset::hms(9, 30, 0)),
),
(
(1942, 2, 9, 3, 0, 0, 0),
o_unambiguous(-Offset::hms(9, 30, 0)),
),
(
(1945, 8, 14, 13, 29, 59, 0),
o_unambiguous(-Offset::hms(9, 30, 0)),
),
(
(1945, 8, 14, 13, 30, 0, 0),
o_unambiguous(-Offset::hms(9, 30, 0)),
),
(
(1945, 8, 14, 13, 30, 1, 0),
o_unambiguous(-Offset::hms(9, 30, 0)),
),
(
(1945, 9, 30, 0, 59, 59, 0),
o_unambiguous(-Offset::hms(9, 30, 0)),
),
(
(1945, 9, 30, 1, 0, 0, 0),
o_fold(
-Offset::hms(9, 30, 0),
-Offset::hms(10, 30, 0),
),
),
(
(1945, 9, 30, 1, 59, 59, 0),
o_fold(
-Offset::hms(9, 30, 0),
-Offset::hms(10, 30, 0),
),
),
(
(1945, 9, 30, 2, 0, 0, 0),
o_unambiguous(-Offset::hms(10, 30, 0)),
),
(
(1947, 6, 8, 1, 59, 59, 0),
o_unambiguous(-Offset::hms(10, 30, 0)),
),
(
(1947, 6, 8, 2, 0, 0, 0),
o_gap(-Offset::hms(10, 30, 0), -offset(10)),
),
(
(1947, 6, 8, 2, 29, 59, 0),
o_gap(-Offset::hms(10, 30, 0), -offset(10)),
),
((1947, 6, 8, 2, 30, 0, 0), unambiguous(-10)),
],
),
];
for &(tzname, datetimes_to_ambiguous) in tests {
let test_file = TzifTestFile::get(tzname);
let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
for &(datetime, ambiguous_kind) in datetimes_to_ambiguous {
let (year, month, day, hour, min, sec, nano) = datetime;
let dt = date(year, month, day).at(hour, min, sec, nano);
let got = tz.to_ambiguous_zoned(dt);
assert_eq!(
got.offset(),
ambiguous_kind,
"\nTZ: {tzname}\ndatetime: \
{year:04}-{month:02}-{day:02}T\
{hour:02}:{min:02}:{sec:02}.{nano:09}",
);
}
}
}
#[test]
fn time_zone_tzif_to_datetime() {
let o = |hours| offset(hours);
let tests: &[(&str, &[_])] = &[
(
"America/New_York",
&[
((0, 0), o(-5), "EST", (1969, 12, 31, 19, 0, 0, 0)),
(
(1710052200, 0),
o(-5),
"EST",
(2024, 3, 10, 1, 30, 0, 0),
),
(
(1710053999, 999_999_999),
o(-5),
"EST",
(2024, 3, 10, 1, 59, 59, 999_999_999),
),
((1710054000, 0), o(-4), "EDT", (2024, 3, 10, 3, 0, 0, 0)),
(
(1710055800, 0),
o(-4),
"EDT",
(2024, 3, 10, 3, 30, 0, 0),
),
((1730610000, 0), o(-4), "EDT", (2024, 11, 3, 1, 0, 0, 0)),
(
(1730611800, 0),
o(-4),
"EDT",
(2024, 11, 3, 1, 30, 0, 0),
),
(
(1730613599, 999_999_999),
o(-4),
"EDT",
(2024, 11, 3, 1, 59, 59, 999_999_999),
),
((1730613600, 0), o(-5), "EST", (2024, 11, 3, 1, 0, 0, 0)),
(
(1730615400, 0),
o(-5),
"EST",
(2024, 11, 3, 1, 30, 0, 0),
),
],
),
(
"Australia/Tasmania",
&[
((0, 0), o(11), "AEDT", (1970, 1, 1, 11, 0, 0, 0)),
(
(1728142200, 0),
o(10),
"AEST",
(2024, 10, 6, 1, 30, 0, 0),
),
(
(1728143999, 999_999_999),
o(10),
"AEST",
(2024, 10, 6, 1, 59, 59, 999_999_999),
),
(
(1728144000, 0),
o(11),
"AEDT",
(2024, 10, 6, 3, 0, 0, 0),
),
(
(1728145800, 0),
o(11),
"AEDT",
(2024, 10, 6, 3, 30, 0, 0),
),
((1712415600, 0), o(11), "AEDT", (2024, 4, 7, 2, 0, 0, 0)),
(
(1712417400, 0),
o(11),
"AEDT",
(2024, 4, 7, 2, 30, 0, 0),
),
(
(1712419199, 999_999_999),
o(11),
"AEDT",
(2024, 4, 7, 2, 59, 59, 999_999_999),
),
((1712419200, 0), o(10), "AEST", (2024, 4, 7, 2, 0, 0, 0)),
(
(1712421000, 0),
o(10),
"AEST",
(2024, 4, 7, 2, 30, 0, 0),
),
],
),
// Pacific/Honolulu is small eough that we just test every
// possible instant before, at and after each transition.
(
"Pacific/Honolulu",
&[
(
(-2334101315, 0),
-Offset::hms(10, 31, 26),
"LMT",
(1896, 1, 13, 11, 59, 59, 0),
),
(
(-2334101314, 0),
-Offset::hms(10, 30, 0),
"HST",
(1896, 1, 13, 12, 1, 26, 0),
),
(
(-2334101313, 0),
-Offset::hms(10, 30, 0),
"HST",
(1896, 1, 13, 12, 1, 27, 0),
),
(
(-1157283001, 0),
-Offset::hms(10, 30, 0),
"HST",
(1933, 4, 30, 1, 59, 59, 0),
),
(
(-1157283000, 0),
-Offset::hms(9, 30, 0),
"HDT",
(1933, 4, 30, 3, 0, 0, 0),
),
(
(-1157282999, 0),
-Offset::hms(9, 30, 0),
"HDT",
(1933, 4, 30, 3, 0, 1, 0),
),
(
(-1155436201, 0),
-Offset::hms(9, 30, 0),
"HDT",
(1933, 5, 21, 11, 59, 59, 0),
),
(
(-1155436200, 0),
-Offset::hms(10, 30, 0),
"HST",
(1933, 5, 21, 11, 0, 0, 0),
),
(
(-1155436199, 0),
-Offset::hms(10, 30, 0),
"HST",
(1933, 5, 21, 11, 0, 1, 0),
),
(
(-880198201, 0),
-Offset::hms(10, 30, 0),
"HST",
(1942, 2, 9, 1, 59, 59, 0),
),
(
(-880198200, 0),
-Offset::hms(9, 30, 0),
"HWT",
(1942, 2, 9, 3, 0, 0, 0),
),
(
(-880198199, 0),
-Offset::hms(9, 30, 0),
"HWT",
(1942, 2, 9, 3, 0, 1, 0),
),
(
(-769395601, 0),
-Offset::hms(9, 30, 0),
"HWT",
(1945, 8, 14, 13, 29, 59, 0),
),
(
(-769395600, 0),
-Offset::hms(9, 30, 0),
"HPT",
(1945, 8, 14, 13, 30, 0, 0),
),
(
(-769395599, 0),
-Offset::hms(9, 30, 0),
"HPT",
(1945, 8, 14, 13, 30, 1, 0),
),
(
(-765376201, 0),
-Offset::hms(9, 30, 0),
"HPT",
(1945, 9, 30, 1, 59, 59, 0),
),
(
(-765376200, 0),
-Offset::hms(10, 30, 0),
"HST",
(1945, 9, 30, 1, 0, 0, 0),
),
(
(-765376199, 0),
-Offset::hms(10, 30, 0),
"HST",
(1945, 9, 30, 1, 0, 1, 0),
),
(
(-712150201, 0),
-Offset::hms(10, 30, 0),
"HST",
(1947, 6, 8, 1, 59, 59, 0),
),
// At this point, we hit the last transition and the POSIX
// TZ string takes over.
(
(-712150200, 0),
-Offset::hms(10, 0, 0),
"HST",
(1947, 6, 8, 2, 30, 0, 0),
),
(
(-712150199, 0),
-Offset::hms(10, 0, 0),
"HST",
(1947, 6, 8, 2, 30, 1, 0),
),
],
),
// This time zone has an interesting transition where it jumps
// backwards a full day at 1867-10-19T15:30:00.
(
"America/Sitka",
&[
((0, 0), o(-8), "PST", (1969, 12, 31, 16, 0, 0, 0)),
(
(-377705023201, 0),
Offset::hms(14, 58, 47),
"LMT",
(-9999, 1, 2, 16, 58, 46, 0),
),
(
(-3225223728, 0),
Offset::hms(14, 58, 47),
"LMT",
(1867, 10, 19, 15, 29, 59, 0),
),
// Notice the 24 hour time jump backwards a whole day!
(
(-3225223727, 0),
-Offset::hms(9, 1, 13),
"LMT",
(1867, 10, 18, 15, 30, 0, 0),
),
(
(-3225223726, 0),
-Offset::hms(9, 1, 13),
"LMT",
(1867, 10, 18, 15, 30, 1, 0),
),
],
),
];
for &(tzname, timestamps_to_datetimes) in tests {
let test_file = TzifTestFile::get(tzname);
let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
for &((unix_sec, unix_nano), offset, abbrev, datetime) in
timestamps_to_datetimes
{
let (year, month, day, hour, min, sec, nano) = datetime;
let timestamp = Timestamp::new(unix_sec, unix_nano).unwrap();
let (got_offset, _, got_abbrev) = tz.to_offset(timestamp);
assert_eq!(
got_offset, offset,
"\nTZ={tzname}, timestamp({unix_sec}, {unix_nano})",
);
assert_eq!(
got_abbrev, abbrev,
"\nTZ={tzname}, timestamp({unix_sec}, {unix_nano})",
);
assert_eq!(
got_offset.to_datetime(timestamp),
date(year, month, day).at(hour, min, sec, nano),
"\nTZ={tzname}, timestamp({unix_sec}, {unix_nano})",
);
}
}
}
#[test]
fn time_zone_posix_to_ambiguous_timestamp() {
let tests: &[(&str, &[_])] = &[
// America/New_York, but a utopia in which DST is abolished.
(
"EST5",
&[
((1969, 12, 31, 19, 0, 0, 0), unambiguous(-5)),
((2024, 3, 10, 2, 0, 0, 0), unambiguous(-5)),
],
),
// The standard DST rule for America/New_York.
(
"EST5EDT,M3.2.0,M11.1.0",
&[
((1969, 12, 31, 19, 0, 0, 0), unambiguous(-5)),
((2024, 3, 10, 1, 59, 59, 999_999_999), unambiguous(-5)),
((2024, 3, 10, 2, 0, 0, 0), gap(-5, -4)),
((2024, 3, 10, 2, 59, 59, 999_999_999), gap(-5, -4)),
((2024, 3, 10, 3, 0, 0, 0), unambiguous(-4)),
((2024, 11, 3, 0, 59, 59, 999_999_999), unambiguous(-4)),
((2024, 11, 3, 1, 0, 0, 0), fold(-4, -5)),
((2024, 11, 3, 1, 59, 59, 999_999_999), fold(-4, -5)),
((2024, 11, 3, 2, 0, 0, 0), unambiguous(-5)),
],
),
// A bit of a nonsensical America/New_York that has DST, but whose
// offset is equivalent to standard time. Having the same offset
// means there's never any ambiguity.
(
"EST5EDT5,M3.2.0,M11.1.0",
&[
((1969, 12, 31, 19, 0, 0, 0), unambiguous(-5)),
((2024, 3, 10, 1, 59, 59, 999_999_999), unambiguous(-5)),
((2024, 3, 10, 2, 0, 0, 0), unambiguous(-5)),
((2024, 3, 10, 2, 59, 59, 999_999_999), unambiguous(-5)),
((2024, 3, 10, 3, 0, 0, 0), unambiguous(-5)),
((2024, 11, 3, 0, 59, 59, 999_999_999), unambiguous(-5)),
((2024, 11, 3, 1, 0, 0, 0), unambiguous(-5)),
((2024, 11, 3, 1, 59, 59, 999_999_999), unambiguous(-5)),
((2024, 11, 3, 2, 0, 0, 0), unambiguous(-5)),
],
),
// This is Europe/Dublin's rule. It's interesting because its
// DST is an offset behind standard time. (DST is usually one hour
// ahead of standard time.)
(
"IST-1GMT0,M10.5.0,M3.5.0/1",
&[
((1970, 1, 1, 0, 0, 0, 0), unambiguous(0)),
((2024, 3, 31, 0, 59, 59, 999_999_999), unambiguous(0)),
((2024, 3, 31, 1, 0, 0, 0), gap(0, 1)),
((2024, 3, 31, 1, 59, 59, 999_999_999), gap(0, 1)),
((2024, 3, 31, 2, 0, 0, 0), unambiguous(1)),
((2024, 10, 27, 0, 59, 59, 999_999_999), unambiguous(1)),
((2024, 10, 27, 1, 0, 0, 0), fold(1, 0)),
((2024, 10, 27, 1, 59, 59, 999_999_999), fold(1, 0)),
((2024, 10, 27, 2, 0, 0, 0), unambiguous(0)),
],
),
// This is Australia/Tasmania's rule. We chose this because it's
// in the southern hemisphere where DST still skips ahead one hour,
// but it usually starts in the fall and ends in the spring.
(
"AEST-10AEDT,M10.1.0,M4.1.0/3",
&[
((1970, 1, 1, 11, 0, 0, 0), unambiguous(11)),
((2024, 4, 7, 1, 59, 59, 999_999_999), unambiguous(11)),
((2024, 4, 7, 2, 0, 0, 0), fold(11, 10)),
((2024, 4, 7, 2, 59, 59, 999_999_999), fold(11, 10)),
((2024, 4, 7, 3, 0, 0, 0), unambiguous(10)),
((2024, 10, 6, 1, 59, 59, 999_999_999), unambiguous(10)),
((2024, 10, 6, 2, 0, 0, 0), gap(10, 11)),
((2024, 10, 6, 2, 59, 59, 999_999_999), gap(10, 11)),
((2024, 10, 6, 3, 0, 0, 0), unambiguous(11)),
],
),
// This is Antarctica/Troll's rule. We chose this one because its
// DST transition is 2 hours instead of the standard 1 hour. This
// means gaps and folds are twice as long as they usually are. And
// it means there are 22 hour and 26 hour days, respectively. Wow!
(
"<+00>0<+02>-2,M3.5.0/1,M10.5.0/3",
&[
((1970, 1, 1, 0, 0, 0, 0), unambiguous(0)),
// test the gap
((2024, 3, 31, 0, 59, 59, 999_999_999), unambiguous(0)),
((2024, 3, 31, 1, 0, 0, 0), gap(0, 2)),
((2024, 3, 31, 1, 59, 59, 999_999_999), gap(0, 2)),
// still in the gap!
((2024, 3, 31, 2, 0, 0, 0), gap(0, 2)),
((2024, 3, 31, 2, 59, 59, 999_999_999), gap(0, 2)),
// finally out
((2024, 3, 31, 3, 0, 0, 0), unambiguous(2)),
// test the fold
((2024, 10, 27, 0, 59, 59, 999_999_999), unambiguous(2)),
((2024, 10, 27, 1, 0, 0, 0), fold(2, 0)),
((2024, 10, 27, 1, 59, 59, 999_999_999), fold(2, 0)),
// still in the fold!
((2024, 10, 27, 2, 0, 0, 0), fold(2, 0)),
((2024, 10, 27, 2, 59, 59, 999_999_999), fold(2, 0)),
// finally out
((2024, 10, 27, 3, 0, 0, 0), unambiguous(0)),
],
),
// This is America/St_Johns' rule, which has an offset with
// non-zero minutes *and* a DST transition rule. (Indian Standard
// Time is the one I'm more familiar with, but it turns out IST
// does not have DST!)
(
"NST3:30NDT,M3.2.0,M11.1.0",
&[
(
(1969, 12, 31, 20, 30, 0, 0),
o_unambiguous(-Offset::hms(3, 30, 0)),
),
(
(2024, 3, 10, 1, 59, 59, 999_999_999),
o_unambiguous(-Offset::hms(3, 30, 0)),
),
(
(2024, 3, 10, 2, 0, 0, 0),
o_gap(-Offset::hms(3, 30, 0), -Offset::hms(2, 30, 0)),
),
(
(2024, 3, 10, 2, 59, 59, 999_999_999),
o_gap(-Offset::hms(3, 30, 0), -Offset::hms(2, 30, 0)),
),
(
(2024, 3, 10, 3, 0, 0, 0),
o_unambiguous(-Offset::hms(2, 30, 0)),
),
(
(2024, 11, 3, 0, 59, 59, 999_999_999),
o_unambiguous(-Offset::hms(2, 30, 0)),
),
(
(2024, 11, 3, 1, 0, 0, 0),
o_fold(-Offset::hms(2, 30, 0), -Offset::hms(3, 30, 0)),
),
(
(2024, 11, 3, 1, 59, 59, 999_999_999),
o_fold(-Offset::hms(2, 30, 0), -Offset::hms(3, 30, 0)),
),
(
(2024, 11, 3, 2, 0, 0, 0),
o_unambiguous(-Offset::hms(3, 30, 0)),
),
],
),
];
for &(posix_tz, datetimes_to_ambiguous) in tests {
let tz = TimeZone::posix(posix_tz).unwrap();
for &(datetime, ambiguous_kind) in datetimes_to_ambiguous {
let (year, month, day, hour, min, sec, nano) = datetime;
let dt = date(year, month, day).at(hour, min, sec, nano);
let got = tz.to_ambiguous_zoned(dt);
assert_eq!(
got.offset(),
ambiguous_kind,
"\nTZ: {posix_tz}\ndatetime: \
{year:04}-{month:02}-{day:02}T\
{hour:02}:{min:02}:{sec:02}.{nano:09}",
);
}
}
}
#[test]
fn time_zone_posix_to_datetime() {
let o = |hours| offset(hours);
let tests: &[(&str, &[_])] = &[
("EST5", &[((0, 0), o(-5), (1969, 12, 31, 19, 0, 0, 0))]),
(
// From America/New_York
"EST5EDT,M3.2.0,M11.1.0",
&[
((0, 0), o(-5), (1969, 12, 31, 19, 0, 0, 0)),
((1710052200, 0), o(-5), (2024, 3, 10, 1, 30, 0, 0)),
(
(1710053999, 999_999_999),
o(-5),
(2024, 3, 10, 1, 59, 59, 999_999_999),
),
((1710054000, 0), o(-4), (2024, 3, 10, 3, 0, 0, 0)),
((1710055800, 0), o(-4), (2024, 3, 10, 3, 30, 0, 0)),
((1730610000, 0), o(-4), (2024, 11, 3, 1, 0, 0, 0)),
((1730611800, 0), o(-4), (2024, 11, 3, 1, 30, 0, 0)),
(
(1730613599, 999_999_999),
o(-4),
(2024, 11, 3, 1, 59, 59, 999_999_999),
),
((1730613600, 0), o(-5), (2024, 11, 3, 1, 0, 0, 0)),
((1730615400, 0), o(-5), (2024, 11, 3, 1, 30, 0, 0)),
],
),
(
// From Australia/Tasmania
//
// We chose this because it's a time zone in the southern
// hemisphere with DST. Unlike the northern hemisphere, its DST
// starts in the fall and ends in the spring. In the northern
// hemisphere, we typically start DST in the spring and end it
// in the fall.
"AEST-10AEDT,M10.1.0,M4.1.0/3",
&[
((0, 0), o(11), (1970, 1, 1, 11, 0, 0, 0)),
((1728142200, 0), o(10), (2024, 10, 6, 1, 30, 0, 0)),
(
(1728143999, 999_999_999),
o(10),
(2024, 10, 6, 1, 59, 59, 999_999_999),
),
((1728144000, 0), o(11), (2024, 10, 6, 3, 0, 0, 0)),
((1728145800, 0), o(11), (2024, 10, 6, 3, 30, 0, 0)),
((1712415600, 0), o(11), (2024, 4, 7, 2, 0, 0, 0)),
((1712417400, 0), o(11), (2024, 4, 7, 2, 30, 0, 0)),
(
(1712419199, 999_999_999),
o(11),
(2024, 4, 7, 2, 59, 59, 999_999_999),
),
((1712419200, 0), o(10), (2024, 4, 7, 2, 0, 0, 0)),
((1712421000, 0), o(10), (2024, 4, 7, 2, 30, 0, 0)),
],
),
(
// Uses the maximum possible offset. A sloppy read of POSIX
// seems to indicate the maximum offset is 24:59:59, but since
// DST defaults to 1 hour ahead of standard time, it's possible
// to use 24:59:59 for standard time, omit the DST offset, and
// thus get a DST offset of 25:59:59.
"XXX-24:59:59YYY,M3.2.0,M11.1.0",
&[
// 2024-01-05T00:00:00+00
(
(1704412800, 0),
Offset::hms(24, 59, 59),
(2024, 1, 6, 0, 59, 59, 0),
),
// 2024-06-05T00:00:00+00 (DST)
(
(1717545600, 0),
Offset::hms(25, 59, 59),
(2024, 6, 6, 1, 59, 59, 0),
),
],
),
];
for &(posix_tz, timestamps_to_datetimes) in tests {
let tz = TimeZone::posix(posix_tz).unwrap();
for &((unix_sec, unix_nano), offset, datetime) in
timestamps_to_datetimes
{
let (year, month, day, hour, min, sec, nano) = datetime;
let timestamp = Timestamp::new(unix_sec, unix_nano).unwrap();
assert_eq!(
tz.to_offset(timestamp).0,
offset,
"\ntimestamp({unix_sec}, {unix_nano})",
);
assert_eq!(
tz.to_datetime(timestamp),
date(year, month, day).at(hour, min, sec, nano),
"\ntimestamp({unix_sec}, {unix_nano})",
);
}
}
}
#[test]
fn time_zone_fixed_to_datetime() {
let tz = offset(-5).to_time_zone();
let unix_epoch = Timestamp::new(0, 0).unwrap();
assert_eq!(
tz.to_datetime(unix_epoch),
date(1969, 12, 31).at(19, 0, 0, 0),
);
let tz = Offset::from_seconds(93_599).unwrap().to_time_zone();
let timestamp = Timestamp::new(253402207200, 999_999_999).unwrap();
assert_eq!(
tz.to_datetime(timestamp),
date(9999, 12, 31).at(23, 59, 59, 999_999_999),
);
let tz = Offset::from_seconds(-93_599).unwrap().to_time_zone();
let timestamp = Timestamp::new(-377705023201, 0).unwrap();
assert_eq!(
tz.to_datetime(timestamp),
date(-9999, 1, 1).at(0, 0, 0, 0),
);
}
#[test]
fn time_zone_fixed_to_timestamp() {
let tz = offset(-5).to_time_zone();
let dt = date(1969, 12, 31).at(19, 0, 0, 0);
assert_eq!(
tz.to_zoned(dt).unwrap().timestamp(),
Timestamp::new(0, 0).unwrap()
);
let tz = Offset::from_seconds(93_599).unwrap().to_time_zone();
let dt = date(9999, 12, 31).at(23, 59, 59, 999_999_999);
assert_eq!(
tz.to_zoned(dt).unwrap().timestamp(),
Timestamp::new(253402207200, 999_999_999).unwrap(),
);
let tz = Offset::from_seconds(93_598).unwrap().to_time_zone();
assert!(tz.to_zoned(dt).is_err());
let tz = Offset::from_seconds(-93_599).unwrap().to_time_zone();
let dt = date(-9999, 1, 1).at(0, 0, 0, 0);
assert_eq!(
tz.to_zoned(dt).unwrap().timestamp(),
Timestamp::new(-377705023201, 0).unwrap(),
);
let tz = Offset::from_seconds(-93_598).unwrap().to_time_zone();
assert!(tz.to_zoned(dt).is_err());
}
#[test]
fn time_zone_tzif_previous_transition() {
let tests: &[(&str, &[(&str, Option<&str>)])] = &[
(
"UTC",
&[
("1969-12-31T19Z", None),
("2024-03-10T02Z", None),
("-009999-12-01 00Z", None),
("9999-12-01 00Z", None),
],
),
(
"America/New_York",
&[
("2024-03-10 08Z", Some("2024-03-10 07Z")),
("2024-03-10 07:00:00.000000001Z", Some("2024-03-10 07Z")),
("2024-03-10 07Z", Some("2023-11-05 06Z")),
("2023-11-05 06Z", Some("2023-03-12 07Z")),
("-009999-01-31 00Z", None),
("9999-12-01 00Z", Some("9999-11-07 06Z")),
// While at present we have "fat" TZif files for our
// testdata, it's conceivable they could be swapped to
// "slim." In which case, the tests above will mostly just
// be testing POSIX TZ strings and not the TZif logic. So
// below, we include times that will be in slim (i.e.,
// historical times the precede the current DST rule).
("1969-12-31 19Z", Some("1969-10-26 06Z")),
("2000-04-02 08Z", Some("2000-04-02 07Z")),
("2000-04-02 07:00:00.000000001Z", Some("2000-04-02 07Z")),
("2000-04-02 07Z", Some("1999-10-31 06Z")),
("1999-10-31 06Z", Some("1999-04-04 07Z")),
],
),
(
"Australia/Tasmania",
&[
("2010-04-03 17Z", Some("2010-04-03 16Z")),
("2010-04-03 16:00:00.000000001Z", Some("2010-04-03 16Z")),
("2010-04-03 16Z", Some("2009-10-03 16Z")),
("2009-10-03 16Z", Some("2009-04-04 16Z")),
("-009999-01-31 00Z", None),
("9999-12-01 00Z", Some("9999-10-02 16Z")),
// Tests for historical data from tzdb. No POSIX TZ.
("2000-03-25 17Z", Some("2000-03-25 16Z")),
("2000-03-25 16:00:00.000000001Z", Some("2000-03-25 16Z")),
("2000-03-25 16Z", Some("1999-10-02 16Z")),
("1999-10-02 16Z", Some("1999-03-27 16Z")),
],
),
// This is Europe/Dublin's rule. It's interesting because its
// DST is an offset behind standard time. (DST is usually one hour
// ahead of standard time.)
(
"Europe/Dublin",
&[
("2010-03-28 02Z", Some("2010-03-28 01Z")),
("2010-03-28 01:00:00.000000001Z", Some("2010-03-28 01Z")),
("2010-03-28 01Z", Some("2009-10-25 01Z")),
("2009-10-25 01Z", Some("2009-03-29 01Z")),
("-009999-01-31 00Z", None),
("9999-12-01 00Z", Some("9999-10-31 01Z")),
// Tests for historical data from tzdb. No POSIX TZ.
("1990-03-25 02Z", Some("1990-03-25 01Z")),
("1990-03-25 01:00:00.000000001Z", Some("1990-03-25 01Z")),
("1990-03-25 01Z", Some("1989-10-29 01Z")),
("1989-10-25 01Z", Some("1989-03-26 01Z")),
],
),
];
for &(tzname, prev_trans) in tests {
let test_file = TzifTestFile::get(tzname);
let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
for (given, expected) in prev_trans {
let given: Timestamp = given.parse().unwrap();
let expected =
expected.map(|s| s.parse::<Timestamp>().unwrap());
let got = tz.previous_transition(given);
assert_eq!(got, expected, "\nTZ: {tzname}\ngiven: {given}");
}
}
}
#[test]
fn time_zone_tzif_next_transition() {
let tests: &[(&str, &[(&str, Option<&str>)])] = &[
(
"UTC",
&[
("1969-12-31T19Z", None),
("2024-03-10T02Z", None),
("-009999-12-01 00Z", None),
("9999-12-01 00Z", None),
],
),
(
"America/New_York",
&[
("2024-03-10 06Z", Some("2024-03-10 07Z")),
("2024-03-10 06:59:59.999999999Z", Some("2024-03-10 07Z")),
("2024-03-10 07Z", Some("2024-11-03 06Z")),
("2024-11-03 06Z", Some("2025-03-09 07Z")),
("-009999-12-01 00Z", Some("1883-11-18 17Z")),
("9999-12-01 00Z", None),
// While at present we have "fat" TZif files for our
// testdata, it's conceivable they could be swapped to
// "slim." In which case, the tests above will mostly just
// be testing POSIX TZ strings and not the TZif logic. So
// below, we include times that will be in slim (i.e.,
// historical times the precede the current DST rule).
("1969-12-31 19Z", Some("1970-04-26 07Z")),
("2000-04-02 06Z", Some("2000-04-02 07Z")),
("2000-04-02 06:59:59.999999999Z", Some("2000-04-02 07Z")),
("2000-04-02 07Z", Some("2000-10-29 06Z")),
("2000-10-29 06Z", Some("2001-04-01 07Z")),
],
),
(
"Australia/Tasmania",
&[
("2010-04-03 15Z", Some("2010-04-03 16Z")),
("2010-04-03 15:59:59.999999999Z", Some("2010-04-03 16Z")),
("2010-04-03 16Z", Some("2010-10-02 16Z")),
("2010-10-02 16Z", Some("2011-04-02 16Z")),
("-009999-12-01 00Z", Some("1895-08-31 14:10:44Z")),
("9999-12-01 00Z", None),
// Tests for historical data from tzdb. No POSIX TZ.
("2000-03-25 15Z", Some("2000-03-25 16Z")),
("2000-03-25 15:59:59.999999999Z", Some("2000-03-25 16Z")),
("2000-03-25 16Z", Some("2000-08-26 16Z")),
("2000-08-26 16Z", Some("2001-03-24 16Z")),
],
),
(
"Europe/Dublin",
&[
("2010-03-28 00Z", Some("2010-03-28 01Z")),
("2010-03-28 00:59:59.999999999Z", Some("2010-03-28 01Z")),
("2010-03-28 01Z", Some("2010-10-31 01Z")),
("2010-10-31 01Z", Some("2011-03-27 01Z")),
("-009999-12-01 00Z", Some("1880-08-02 00:25:21Z")),
("9999-12-01 00Z", None),
// Tests for historical data from tzdb. No POSIX TZ.
("1990-03-25 00Z", Some("1990-03-25 01Z")),
("1990-03-25 00:59:59.999999999Z", Some("1990-03-25 01Z")),
("1990-03-25 01Z", Some("1990-10-28 01Z")),
("1990-10-28 01Z", Some("1991-03-31 01Z")),
],
),
];
for &(tzname, next_trans) in tests {
let test_file = TzifTestFile::get(tzname);
let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
for (given, expected) in next_trans {
let given: Timestamp = given.parse().unwrap();
let expected =
expected.map(|s| s.parse::<Timestamp>().unwrap());
let got = tz.next_transition(given);
assert_eq!(got, expected, "\nTZ: {tzname}\ngiven: {given}");
}
}
}
#[test]
fn time_zone_posix_previous_transition() {
let tests: &[(&str, &[(&str, Option<&str>)])] = &[
// America/New_York, but a utopia in which DST is abolished. There
// are no time zone transitions, so next_transition always returns
// None.
(
"EST5",
&[
("1969-12-31T19Z", None),
("2024-03-10T02Z", None),
("-009999-12-01 00Z", None),
("9999-12-01 00Z", None),
],
),
// The standard DST rule for America/New_York.
(
"EST5EDT,M3.2.0,M11.1.0",
&[
("1969-12-31 19Z", Some("1969-11-02 06Z")),
("2024-03-10 08Z", Some("2024-03-10 07Z")),
("2024-03-10 07:00:00.000000001Z", Some("2024-03-10 07Z")),
("2024-03-10 07Z", Some("2023-11-05 06Z")),
("2023-11-05 06Z", Some("2023-03-12 07Z")),
("-009999-01-31 00Z", None),
("9999-12-01 00Z", Some("9999-11-07 06Z")),
],
),
(
// From Australia/Tasmania
"AEST-10AEDT,M10.1.0,M4.1.0/3",
&[
("2010-04-03 17Z", Some("2010-04-03 16Z")),
("2010-04-03 16:00:00.000000001Z", Some("2010-04-03 16Z")),
("2010-04-03 16Z", Some("2009-10-03 16Z")),
("2009-10-03 16Z", Some("2009-04-04 16Z")),
("-009999-01-31 00Z", None),
("9999-12-01 00Z", Some("9999-10-02 16Z")),
],
),
// This is Europe/Dublin's rule. It's interesting because its
// DST is an offset behind standard time. (DST is usually one hour
// ahead of standard time.)
(
"IST-1GMT0,M10.5.0,M3.5.0/1",
&[
("2010-03-28 02Z", Some("2010-03-28 01Z")),
("2010-03-28 01:00:00.000000001Z", Some("2010-03-28 01Z")),
("2010-03-28 01Z", Some("2009-10-25 01Z")),
("2009-10-25 01Z", Some("2009-03-29 01Z")),
("-009999-01-31 00Z", None),
("9999-12-01 00Z", Some("9999-10-31 01Z")),
],
),
];
for &(posix_tz, prev_trans) in tests {
let tz = TimeZone::posix(posix_tz).unwrap();
for (given, expected) in prev_trans {
let given: Timestamp = given.parse().unwrap();
let expected =
expected.map(|s| s.parse::<Timestamp>().unwrap());
let got = tz.previous_transition(given);
assert_eq!(got, expected, "\nTZ: {posix_tz}\ngiven: {given}");
}
}
}
#[test]
fn time_zone_posix_next_transition() {
let tests: &[(&str, &[(&str, Option<&str>)])] = &[
// America/New_York, but a utopia in which DST is abolished. There
// are no time zone transitions, so next_transition always returns
// None.
(
"EST5",
&[
("1969-12-31T19Z", None),
("2024-03-10T02Z", None),
("-009999-12-01 00Z", None),
("9999-12-01 00Z", None),
],
),
// The standard DST rule for America/New_York.
(
"EST5EDT,M3.2.0,M11.1.0",
&[
("1969-12-31 19Z", Some("1970-03-08 07Z")),
("2024-03-10 06Z", Some("2024-03-10 07Z")),
("2024-03-10 06:59:59.999999999Z", Some("2024-03-10 07Z")),
("2024-03-10 07Z", Some("2024-11-03 06Z")),
("2024-11-03 06Z", Some("2025-03-09 07Z")),
("-009999-12-01 00Z", Some("-009998-03-10 07Z")),
("9999-12-01 00Z", None),
],
),
(
// From Australia/Tasmania
"AEST-10AEDT,M10.1.0,M4.1.0/3",
&[
("2010-04-03 15Z", Some("2010-04-03 16Z")),
("2010-04-03 15:59:59.999999999Z", Some("2010-04-03 16Z")),
("2010-04-03 16Z", Some("2010-10-02 16Z")),
("2010-10-02 16Z", Some("2011-04-02 16Z")),
("-009999-12-01 00Z", Some("-009998-04-06 16Z")),
("9999-12-01 00Z", None),
],
),
// This is Europe/Dublin's rule. It's interesting because its
// DST is an offset behind standard time. (DST is usually one hour
// ahead of standard time.)
(
"IST-1GMT0,M10.5.0,M3.5.0/1",
&[
("2010-03-28 00Z", Some("2010-03-28 01Z")),
("2010-03-28 00:59:59.999999999Z", Some("2010-03-28 01Z")),
("2010-03-28 01Z", Some("2010-10-31 01Z")),
("2010-10-31 01Z", Some("2011-03-27 01Z")),
("-009999-12-01 00Z", Some("-009998-03-31 01Z")),
("9999-12-01 00Z", None),
],
),
];
for &(posix_tz, next_trans) in tests {
let tz = TimeZone::posix(posix_tz).unwrap();
for (given, expected) in next_trans {
let given: Timestamp = given.parse().unwrap();
let expected =
expected.map(|s| s.parse::<Timestamp>().unwrap());
let got = tz.next_transition(given);
assert_eq!(got, expected, "\nTZ: {posix_tz}\ngiven: {given}");
}
}
}
/// This tests that the size of a time zone is kept at a single word.
///
/// This is important because every jiff::Zoned has a TimeZone inside of
/// it, and we want to keep its size as small as we can.
#[test]
fn time_zone_size() {
let word = core::mem::size_of::<usize>();
assert_eq!(word, core::mem::size_of::<TimeZone>());
}
}