jiff/tz/mod.rs
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 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843
/*!
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).in_tz("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 crate::{
civil::DateTime,
error::{err, Error, ErrorContext},
util::{array_str::ArrayStr, sync::Arc},
Timestamp, Zoned,
};
#[cfg(feature = "alloc")]
use self::posix::ReasonablePosixTimeZone;
pub use self::{
db::{db, TimeZoneDatabase, TimeZoneName, TimeZoneNameIter},
offset::{Dst, Offset, OffsetArithmetic, OffsetConflict, OffsetRound},
};
#[cfg(feature = "tzdb-concatenated")]
mod concatenated;
mod db;
mod offset;
#[cfg(feature = "alloc")]
pub(crate) mod posix;
#[cfg(feature = "tz-system")]
mod system;
#[cfg(all(test, feature = "alloc"))]
mod testdata;
#[cfg(feature = "alloc")]
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.in_tz("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.in_tz("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.in_tz("America/New_York")?;
/// let zdt2 = zdt1.in_tz("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`.)
///
/// # A `TimeZone` is cheap to clone
///
/// A `TimeZone` can be cheaply cloned. It uses automic reference counting
/// internally. When `alloc` is disabled, cloning a `TimeZone` is still cheap
/// because POSIX time zones and TZif time zones are unsupported. Therefore,
/// cloning a time zone does a deep copy (since automic reference counting is
/// not available), but the data being copied is small.
///
/// # 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>>(())
/// ```
///
/// # Serde integration
///
/// At present, a `TimeZone` does not implement Serde's `Serialize` or
/// `Deserialize` traits directly. Nor does it implement `std::fmt::Display`
/// or `std::str::FromStr`. The reason for this is that it's not totally
/// clear if there is one single obvious behavior. Moreover, some `TimeZone`
/// values do not have an obvious succinct serialized representation. (For
/// example, when `/etc/localtime` on a Unix system is your system's time zone,
/// and it isn't a symlink to a TZif file in `/usr/share/zoneinfo`. In which
/// case, an IANA time zone identifier cannot easily be deduced by Jiff.)
///
/// Instead, Jiff offers helpers for use with Serde's [`with` attribute] via
/// the [`fmt::serde`](crate::fmt::serde) module:
///
/// ```
/// use jiff::tz::TimeZone;
///
/// #[derive(Debug, serde::Deserialize, serde::Serialize)]
/// struct Record {
/// #[serde(with = "jiff::fmt::serde::tz::optional")]
/// tz: Option<TimeZone>,
/// }
///
/// let json = r#"{"tz":"America/Nuuk"}"#;
/// let got: Record = serde_json::from_str(&json)?;
/// assert_eq!(got.tz, Some(TimeZone::get("America/Nuuk")?));
/// assert_eq!(serde_json::to_string(&got)?, json);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// Alternatively, you may use the
/// [`fmt::temporal::DateTimeParser::parse_time_zone`](crate::fmt::temporal::DateTimeParser::parse_time_zone)
/// or
/// [`fmt::temporal::DateTimePrinter::print_time_zone`](crate::fmt::temporal::DateTimePrinter::print_time_zone)
/// routines to parse or print `TimeZone` values without using Serde.
///
/// [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
/// [`with` attribute]: https://serde.rs/field-attrs.html#with
#[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.
///
/// Detection of a system's default time zone is generally heuristic
/// based and platform specific.
///
/// If callers need to know whether discovery of the system time zone
/// failed, then use [`TimeZone::try_system`].
///
/// # Fallback behavior
///
/// 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::unknown`]. A `WARN` level log will also be emitted with
/// a message explaining why time zone detection failed. The fallback to
/// an unknown time zone is a practical trade-off, is what most other
/// systems tend to do and is also recommended by [relevant standards such
/// as freedesktop.org][freedesktop-org-localtime].
///
/// An unknown time zone _behaves_ like [`TimeZone::UTC`], but will
/// print as `Etc/Unknown` when converting a `Zoned` to a string.
///
/// If you would instead like to fall back to UTC instead
/// of the special "unknown" time zone, then you can do
/// `TimeZone::try_system().unwrap_or(TimeZone::UTC)`.
///
/// # 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 non-Android 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 Android systems, this inspects the `persist.sys.timezone` property.
///
/// 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].
///
/// [freedesktop-org-localtime]: https://www.freedesktop.org/software/systemd/man/latest/localtime.html
/// [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 {
match TimeZone::try_system() {
Ok(tz) => tz,
Err(_err) => {
warn!(
"failed to get system time zone, \
falling back to `Etc/Unknown` \
(which behaves like UTC): {_err}",
);
TimeZone::unknown()
}
}
}
/// 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 an error.
///
/// Detection of a system's default time zone is generally heuristic
/// based and platform specific.
///
/// Note that callers should generally prefer using [`TimeZone::system`].
/// If a system time zone could not be found, then it falls
/// back to [`TimeZone::UTC`] automatically. This is often
/// what is recommended by [relevant standards such as
/// freedesktop.org][freedesktop-org-localtime]. Conversely, this routine
/// is useful if detection of a system's default time zone is critical.
///
/// # 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].
///
/// [freedesktop-org-localtime]: https://www.freedesktop.org/software/systemd/man/latest/localtime.html
/// [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 try_system() -> Result<TimeZone, Error> {
#[cfg(not(feature = "tz-system"))]
{
Err(err!(
"failed to get system time zone since 'tz-system' \
crate feature is not enabled",
))
}
#[cfg(feature = "tz-system")]
{
self::system::get(db())
}
}
/// 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>>(())
/// ```
#[cfg(feature = "alloc")]
pub fn posix(posix_tz_string: &str) -> Result<TimeZone, Error> {
let iana_tz = posix::IanaTz::parse_v3plus(posix_tz_string)?;
let reasonable = iana_tz.into_tz();
Ok(TimeZone::from_reasonable_posix_tz(reasonable))
}
/// Creates a time zone from a POSIX tz. Expose so that other parts of Jiff
/// can create a `TimeZone` from a POSIX tz. (Kinda sloppy to be honest.)
#[cfg(feature = "alloc")]
pub(crate) fn from_reasonable_posix_tz(
posix: ReasonablePosixTimeZone,
) -> TimeZone {
let posix = TimeZonePosix { posix };
let kind = TimeZoneKind::Posix(posix);
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.
#[cfg(feature = "alloc")]
pub fn tzif(name: &str, data: &[u8]) -> Result<TimeZone, Error> {
use alloc::string::ToString;
let tzif = TimeZoneTzif::new(Some(name.to_string()), data)?;
let kind = TimeZoneKind::Tzif(tzif);
Ok(TimeZone { kind: Some(Arc::new(kind)) })
}
/// Returns a `TimeZone` that is specifially marked as "unknown."
///
/// This corresponds to the Unicode CLDR identifier `Etc/Unknown`, which
/// is guaranteed to never be a valid IANA time zone identifier (as of
/// the `2025a` release of tzdb).
///
/// This type of `TimeZone` is used in circumstances where one wants to
/// signal that discovering a time zone failed for some reason, but that
/// execution can reasonably continue. For example, [`TimeZone::system`]
/// returns this type of time zone when the system time zone could not be
/// discovered.
///
/// # Example
///
/// Jiff permits an "unknown" time zone to losslessly be transmitted
/// through serialization:
///
/// ```
/// use jiff::{civil::date, tz::TimeZone, Zoned};
///
/// let tz = TimeZone::unknown();
/// let zdt = date(2025, 2, 1).at(17, 0, 0, 0).to_zoned(tz)?;
/// assert_eq!(zdt.to_string(), "2025-02-01T17:00:00Z[Etc/Unknown]");
/// let got: Zoned = "2025-02-01T17:00:00Z[Etc/Unknown]".parse()?;
/// assert_eq!(got, zdt);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// Note that not all systems support this. Some systems will reject
/// `Etc/Unknown` because it is not a valid IANA time zone identifier and
/// does not have an entry in the IANA time zone database. However, Jiff
/// takes this approach because it surfaces an error condition in detecting
/// the end user's time zone. Callers not wanting an "unknown" time zone
/// can use `TimeZone::try_system().unwrap_or(TimeZone::UTC)` instead of
/// `TimeZone::system`. (Where the latter falls back to the "unknown" time
/// zone when a system configured time zone could not be found.)
pub fn unknown() -> TimeZone {
let kind = TimeZoneKind::Unknown;
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.
#[cfg(feature = "tz-system")]
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) -> DiagnosticName<'_> {
DiagnosticName(self)
}
/// Returns true if and only if this `TimeZone` can be succinctly
/// serialized.
///
/// Basically, this is only `false` when this `TimeZone` was created from
/// a `/etc/localtime` for which a valid IANA time zone identifier could
/// not be extracted. It is also `false` when [`TimeZone::is_unknown`]
/// is `true`.
#[cfg(feature = "serde")]
#[inline]
pub(crate) fn has_succinct_serialization(&self) -> bool {
let Some(ref kind) = self.kind else { return true };
match **kind {
TimeZoneKind::Unknown => true,
TimeZoneKind::Fixed(_) => true,
#[cfg(feature = "alloc")]
TimeZoneKind::Posix(_) => true,
#[cfg(feature = "alloc")]
TimeZoneKind::Tzif(ref tz) => tz.name().is_some(),
}
}
/// 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 {
#[cfg(feature = "alloc")]
TimeZoneKind::Tzif(ref tz) => tz.name(),
// Note that while `Etc/Unknown` looks like an IANA time zone
// identifier, it is specifically and explicitly NOT an IANA time
// zone identifier. So we do not return it here if we have an
// unknown time zone identifier.
_ => None,
}
}
/// Returns true if and only if this time zone is unknown.
///
/// This has the special internal identifier of `Etc/Unknown`, and this
/// is what will be used when converting a `Zoned` to a string.
///
/// Note that while `Etc/Unknown` looks like an IANA time zone identifier,
/// it is specifically and explicitly not one. It is reserved and is
/// guaranteed to never be an IANA time zone identifier.
///
/// An unknown time zone can be created via [`TimeZone::unknown`]. It is
/// also returned by [`TimeZone::system`] when a system configured time
/// zone could not be found.
///
/// # Example
///
/// ```
/// use jiff::tz::TimeZone;
///
/// let tz = TimeZone::unknown();
/// assert_eq!(tz.iana_name(), None);
/// assert!(tz.is_unknown());
/// ```
#[inline]
pub fn is_unknown(&self) -> bool {
let Some(ref kind) = self.kind else { return false };
matches!(**kind, TimeZoneKind::Unknown)
}
/// When this time zone is a POSIX time zone, return it.
///
/// This doesn't attempt to convert other time zones that are representable
/// as POSIX time zones to POSIX time zones (e.g., fixed offset time
/// zones). Instead, this only returns something when the actual
/// representation of the time zone is a POSIX time zone.
#[cfg(feature = "alloc")]
#[inline]
pub(crate) fn posix_tz(&self) -> Option<&ReasonablePosixTimeZone> {
let Some(ref kind) = self.kind else { return None };
match **kind {
#[cfg(feature = "alloc")]
TimeZoneKind::Posix(ref tz) => Some(&tz.posix),
_ => 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.in_tz("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 {
self.to_offset(timestamp).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 = tz.to_offset(ts);
/// assert_eq!(offset, tz::offset(-4));
/// 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 = tz.to_offset(ts);
/// assert_eq!(offset, tz::offset(-5));
/// 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 {
let Some(ref kind) = self.kind else {
return Offset::UTC;
};
match **kind {
TimeZoneKind::Unknown => Offset::UTC,
TimeZoneKind::Fixed(ref tz) => tz.to_offset(),
#[cfg(feature = "alloc")]
TimeZoneKind::Posix(ref tz) => tz.to_offset(_timestamp),
#[cfg(feature = "alloc")]
TimeZoneKind::Tzif(ref tz) => tz.to_offset(_timestamp),
}
}
/// Returns the offset information corresponding to the given timestamp in
/// this time zone. This includes the offset along with daylight saving
/// time status and a time zone abbreviation.
///
/// This is like [`TimeZone::to_offset`], but returns the aforementioned
/// extra data in addition to the offset. This data may, in some cases, be
/// more expensive to compute.
///
/// # 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 info = tz.to_offset_info(ts);
/// assert_eq!(info.offset(), tz::offset(-4));
/// assert_eq!(info.dst(), Dst::Yes);
/// assert_eq!(info.abbreviation(), "EDT");
/// assert_eq!(
/// info.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 info = tz.to_offset_info(ts);
/// assert_eq!(info.offset(), tz::offset(-5));
/// assert_eq!(info.dst(), Dst::No);
/// assert_eq!(info.abbreviation(), "EST");
/// assert_eq!(
/// info.offset().to_datetime(ts).to_string(),
/// "2024-01-10T21:46:44",
/// );
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn to_offset_info<'t>(
&'t self,
_timestamp: Timestamp,
) -> TimeZoneOffsetInfo<'t> {
let Some(ref kind) = self.kind else {
return TimeZoneOffsetInfo {
offset: Offset::UTC,
dst: Dst::No,
abbreviation: TimeZoneAbbreviation::Borrowed("UTC"),
};
};
match **kind {
TimeZoneKind::Unknown => {
TimeZoneOffsetInfo {
offset: Offset::UTC,
dst: Dst::No,
// It'd be kinda nice if this were just `ERR` to
// indicate an error, but I can't find any precedent
// for that. And CLDR says `Etc/Unknown` should behave
// like UTC, so... I guess we use UTC here.
abbreviation: TimeZoneAbbreviation::Borrowed("UTC"),
}
}
TimeZoneKind::Fixed(ref tz) => tz.to_offset_info(),
#[cfg(feature = "alloc")]
TimeZoneKind::Posix(ref tz) => tz.to_offset_info(_timestamp),
#[cfg(feature = "alloc")]
TimeZoneKind::Tzif(ref tz) => tz.to_offset_info(_timestamp),
}
}
/// If this time zone is a fixed offset, then this returns the offset.
/// If this time zone is not a fixed offset, then an error is returned.
///
/// If you just need an offset for a given timestamp, then you can use
/// [`TimeZone::to_offset`]. Or, if you need an offset for a civil
/// datetime, then you can use [`TimeZone::to_ambiguous_timestamp`] or
/// [`TimeZone::to_ambiguous_zoned`], although the result may be ambiguous.
///
/// Generally, this routine is useful when you need to know whether the
/// time zone is fixed, and you want to get the offset without having to
/// specify a timestamp. This is sometimes required for interoperating with
/// other datetime systems that need to distinguish between time zones that
/// are fixed and time zones that are based on rules such as those found in
/// the IANA time zone database.
///
/// # Example
///
/// ```
/// use jiff::tz::{Offset, TimeZone};
///
/// let tz = TimeZone::get("America/New_York")?;
/// // A named time zone is not a fixed offset
/// // and so cannot be converted to an offset
/// // without a timestamp or civil datetime.
/// assert_eq!(
/// tz.to_fixed_offset().unwrap_err().to_string(),
/// "cannot convert non-fixed IANA time zone \
/// to offset without timestamp or civil datetime",
/// );
///
/// let tz = TimeZone::UTC;
/// // UTC is a fixed offset and so can be converted
/// // without a timestamp.
/// assert_eq!(tz.to_fixed_offset()?, Offset::UTC);
///
/// // And of course, creating a time zone from a
/// // fixed offset results in a fixed offset time
/// // zone too:
/// let tz = TimeZone::fixed(jiff::tz::offset(-10));
/// assert_eq!(tz.to_fixed_offset()?, jiff::tz::offset(-10));
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn to_fixed_offset(&self) -> Result<Offset, Error> {
let Some(ref kind) = self.kind else { return Ok(Offset::UTC) };
#[allow(irrefutable_let_patterns)]
match **kind {
TimeZoneKind::Unknown => Ok(Offset::UTC),
TimeZoneKind::Fixed(ref tz) => Ok(tz.to_offset()),
#[cfg(feature = "alloc")]
_ => Err(err!(
"cannot convert non-fixed {kind} time zone to offset \
without timestamp or civil datetime",
kind = self.kind_description(),
)),
}
}
/// 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::Unknown => {
AmbiguousOffset::Unambiguous { offset: Offset::UTC }
}
TimeZoneKind::Fixed(ref tz) => {
AmbiguousOffset::Unambiguous { offset: tz.to_offset() }
}
#[cfg(feature = "alloc")]
TimeZoneKind::Posix(ref tz) => tz.to_ambiguous_kind(dt),
#[cfg(feature = "alloc")]
TimeZoneKind::Tzif(ref tz) => tz.to_ambiguous_kind(dt),
},
};
AmbiguousTimestamp::new(dt, ambiguous_kind)
}
/// Returns an iterator of time zone transitions preceding the given
/// timestamp. The iterator returned yields [`TimeZoneTransition`]
/// elements.
///
/// The order of the iterator returned moves backward through time. If
/// there is a previous transition, then the timestamp of that transition
/// is guaranteed to be strictly less than the timestamp given.
///
/// This is a low level API that you generally shouldn't need. It's
/// useful in cases where you need to know something about the specific
/// instants at which time zone transitions occur. For example, an embedded
/// device might need to be explicitly programmed with daylight saving
/// time transitions. APIs like this enable callers to explore those
/// transitions.
///
/// A time zone transition refers to a specific point in time when the
/// offset from UTC for a particular geographical region changes. This
/// is usually a result of daylight saving time, but it can also occur
/// when a geographic region changes its permanent offset from UTC.
///
/// The iterator returned is not guaranteed to yield any elements. For
/// example, this occurs with a fixed offset time zone. Logically, it
/// would also be possible for the iterator to be infinite, except that
/// eventually the timestamp would overflow Jiff's minimum timestamp
/// value, at which point, iteration stops.
///
/// # Example: time since the previous transition
///
/// This example shows how much time has passed since the previous time
/// zone transition:
///
/// ```
/// use jiff::{Unit, Zoned};
///
/// let now: Zoned = "2024-12-31 18:25-05[US/Eastern]".parse()?;
/// let trans = now.time_zone().preceding(now.timestamp()).next().unwrap();
/// let prev_at = trans.timestamp().to_zoned(now.time_zone().clone());
/// let span = now.since((Unit::Year, &prev_at))?;
/// assert_eq!(format!("{span:#}"), "1mo 27d 17h 25m");
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Example: show the 5 previous time zone transitions
///
/// This shows how to find the 5 preceding time zone transitions (from a
/// particular datetime) for a particular time zone:
///
/// ```
/// use jiff::{tz::offset, Zoned};
///
/// let now: Zoned = "2024-12-31 18:25-05[US/Eastern]".parse()?;
/// let transitions = now
/// .time_zone()
/// .preceding(now.timestamp())
/// .take(5)
/// .map(|t| (
/// t.timestamp().to_zoned(now.time_zone().clone()),
/// t.offset(),
/// t.abbreviation().to_string(),
/// ))
/// .collect::<Vec<_>>();
/// assert_eq!(transitions, vec![
/// ("2024-11-03 01:00-05[US/Eastern]".parse()?, offset(-5), "EST".to_string()),
/// ("2024-03-10 03:00-04[US/Eastern]".parse()?, offset(-4), "EDT".to_string()),
/// ("2023-11-05 01:00-05[US/Eastern]".parse()?, offset(-5), "EST".to_string()),
/// ("2023-03-12 03:00-04[US/Eastern]".parse()?, offset(-4), "EDT".to_string()),
/// ("2022-11-06 01:00-05[US/Eastern]".parse()?, offset(-5), "EST".to_string()),
/// ]);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn preceding<'t>(
&'t self,
timestamp: Timestamp,
) -> TimeZonePrecedingTransitions<'t> {
TimeZonePrecedingTransitions { tz: self, cur: timestamp }
}
/// Returns an iterator of time zone transitions following the given
/// timestamp. The iterator returned yields [`TimeZoneTransition`]
/// elements.
///
/// The order of the iterator returned moves forward through time. If
/// there is a following transition, then the timestamp of that transition
/// is guaranteed to be strictly greater than the timestamp given.
///
/// This is a low level API that you generally shouldn't need. It's
/// useful in cases where you need to know something about the specific
/// instants at which time zone transitions occur. For example, an embedded
/// device might need to be explicitly programmed with daylight saving
/// time transitions. APIs like this enable callers to explore those
/// transitions.
///
/// A time zone transition refers to a specific point in time when the
/// offset from UTC for a particular geographical region changes. This
/// is usually a result of daylight saving time, but it can also occur
/// when a geographic region changes its permanent offset from UTC.
///
/// The iterator returned is not guaranteed to yield any elements. For
/// example, this occurs with a fixed offset time zone. Logically, it
/// would also be possible for the iterator to be infinite, except that
/// eventually the timestamp would overflow Jiff's maximum timestamp
/// value, at which point, iteration stops.
///
/// # Example: time until the next transition
///
/// This example shows how much time is left until the next time zone
/// transition:
///
/// ```
/// use jiff::{Unit, Zoned};
///
/// let now: Zoned = "2024-12-31 18:25-05[US/Eastern]".parse()?;
/// let trans = now.time_zone().following(now.timestamp()).next().unwrap();
/// let next_at = trans.timestamp().to_zoned(now.time_zone().clone());
/// let span = now.until((Unit::Year, &next_at))?;
/// assert_eq!(format!("{span:#}"), "2mo 8d 7h 35m");
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Example: show the 5 next time zone transitions
///
/// This shows how to find the 5 following time zone transitions (from a
/// particular datetime) for a particular time zone:
///
/// ```
/// use jiff::{tz::offset, Zoned};
///
/// let now: Zoned = "2024-12-31 18:25-05[US/Eastern]".parse()?;
/// let transitions = now
/// .time_zone()
/// .following(now.timestamp())
/// .take(5)
/// .map(|t| (
/// t.timestamp().to_zoned(now.time_zone().clone()),
/// t.offset(),
/// t.abbreviation().to_string(),
/// ))
/// .collect::<Vec<_>>();
/// assert_eq!(transitions, vec![
/// ("2025-03-09 03:00-04[US/Eastern]".parse()?, offset(-4), "EDT".to_string()),
/// ("2025-11-02 01:00-05[US/Eastern]".parse()?, offset(-5), "EST".to_string()),
/// ("2026-03-08 03:00-04[US/Eastern]".parse()?, offset(-4), "EDT".to_string()),
/// ("2026-11-01 01:00-05[US/Eastern]".parse()?, offset(-5), "EST".to_string()),
/// ("2027-03-14 03:00-04[US/Eastern]".parse()?, offset(-4), "EDT".to_string()),
/// ]);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn following<'t>(
&'t self,
timestamp: Timestamp,
) -> TimeZoneFollowingTransitions<'t> {
TimeZoneFollowingTransitions { tz: self, cur: timestamp }
}
/// Used by the "preceding transitions" iterator.
#[inline]
fn previous_transition(
&self,
_timestamp: Timestamp,
) -> Option<TimeZoneTransition> {
match **self.kind.as_ref()? {
TimeZoneKind::Unknown => None,
TimeZoneKind::Fixed(_) => None,
#[cfg(feature = "alloc")]
TimeZoneKind::Posix(ref tz) => tz.previous_transition(_timestamp),
#[cfg(feature = "alloc")]
TimeZoneKind::Tzif(ref tz) => tz.previous_transition(_timestamp),
}
}
/// Used by the "following transitions" iterator.
#[inline]
fn next_transition(
&self,
_timestamp: Timestamp,
) -> Option<TimeZoneTransition> {
match **self.kind.as_ref()? {
TimeZoneKind::Unknown => None,
TimeZoneKind::Fixed(_) => None,
#[cfg(feature = "alloc")]
TimeZoneKind::Posix(ref tz) => tz.next_transition(_timestamp),
#[cfg(feature = "alloc")]
TimeZoneKind::Tzif(ref tz) => tz.next_transition(_timestamp),
}
}
/// Returns a short description about the kind of this time zone.
///
/// This is useful in error messages.
fn kind_description(&self) -> &str {
let Some(ref kind) = self.kind else {
return "UTC";
};
match **kind {
TimeZoneKind::Unknown => "Etc/Unknown",
TimeZoneKind::Fixed(_) => "fixed",
#[cfg(feature = "alloc")]
TimeZoneKind::Posix(_) => "POSIX",
#[cfg(feature = "alloc")]
TimeZoneKind::Tzif(_) => "IANA",
}
}
}
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::Unknown => &"Etc/Unknown",
TimeZoneKind::Fixed(ref tz) => tz,
#[cfg(feature = "alloc")]
TimeZoneKind::Posix(ref tz) => tz,
#[cfg(feature = "alloc")]
TimeZoneKind::Tzif(ref tz) => tz,
},
};
f.debug_tuple("TimeZone").field(field).finish()
}
}
#[derive(Debug, Eq, PartialEq)]
#[cfg_attr(not(feature = "alloc"), derive(Clone))]
enum TimeZoneKind {
// It would be nice if we could represent this similarly to
// `TimeZone::UTC`. That is, without putting it behind an `Arc`. But I
// didn't see an easy way to do that while retaining the single-word size
// of `TimeZone` without pointer tagging, since `Arc` only gives the
// compiler a single niche value. Plus, it should be exceptionally rare
// for a unknown time zone to be used anyway. It's generally an error
// condition.
Unknown,
Fixed(TimeZoneFixed),
#[cfg(feature = "alloc")]
Posix(TimeZonePosix),
#[cfg(feature = "alloc")]
Tzif(TimeZoneTzif),
}
#[derive(Clone)]
struct TimeZoneFixed {
offset: Offset,
}
impl TimeZoneFixed {
#[inline]
fn new(offset: Offset) -> TimeZoneFixed {
TimeZoneFixed { offset }
}
#[inline]
fn to_offset(&self) -> Offset {
self.offset
}
#[inline]
fn to_offset_info(&self) -> TimeZoneOffsetInfo<'_> {
let abbreviation =
TimeZoneAbbreviation::Owned(self.offset.to_array_str());
TimeZoneOffsetInfo { offset: self.offset, dst: Dst::No, abbreviation }
}
}
impl core::fmt::Debug for TimeZoneFixed {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_tuple("Fixed").field(&self.to_offset()).finish()
}
}
impl core::fmt::Display for TimeZoneFixed {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
core::fmt::Display::fmt(&self.offset, f)
}
}
impl Eq for TimeZoneFixed {}
impl PartialEq for TimeZoneFixed {
#[inline]
fn eq(&self, rhs: &TimeZoneFixed) -> bool {
self.to_offset() == rhs.to_offset()
}
}
#[cfg(feature = "alloc")]
#[derive(Clone, Eq, PartialEq)]
struct TimeZonePosix {
posix: ReasonablePosixTimeZone,
}
#[cfg(feature = "alloc")]
impl TimeZonePosix {
#[inline]
fn to_offset(&self, timestamp: Timestamp) -> Offset {
self.posix.to_offset(timestamp)
}
#[inline]
fn to_offset_info(&self, timestamp: Timestamp) -> TimeZoneOffsetInfo<'_> {
self.posix.to_offset_info(timestamp)
}
#[inline]
fn to_ambiguous_kind(&self, dt: DateTime) -> AmbiguousOffset {
self.posix.to_ambiguous_kind(dt)
}
#[inline]
fn previous_transition(
&self,
timestamp: Timestamp,
) -> Option<TimeZoneTransition> {
self.posix.previous_transition(timestamp)
}
#[inline]
fn next_transition(
&self,
timestamp: Timestamp,
) -> Option<TimeZoneTransition> {
self.posix.next_transition(timestamp)
}
}
// This is implemented by hand because dumping out the full representation of
// a `ReasonablePosixTimeZone` is way too much noise for users of Jiff.
#[cfg(feature = "alloc")]
impl core::fmt::Debug for TimeZonePosix {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(f, "Posix({})", self.posix)
}
}
#[cfg(feature = "alloc")]
impl core::fmt::Display for TimeZonePosix {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
core::fmt::Display::fmt(&self.posix, f)
}
}
#[cfg(feature = "alloc")]
#[derive(Eq, PartialEq)]
struct TimeZoneTzif {
tzif: self::tzif::Tzif,
}
#[cfg(feature = "alloc")]
impl TimeZoneTzif {
#[inline]
fn new(
name: Option<alloc::string::String>,
bytes: &[u8],
) -> Result<TimeZoneTzif, Error> {
let tzif = self::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 {
self.tzif.to_offset(timestamp)
}
#[inline]
fn to_offset_info(&self, timestamp: Timestamp) -> TimeZoneOffsetInfo<'_> {
self.tzif.to_offset_info(timestamp)
}
#[inline]
fn to_ambiguous_kind(&self, dt: DateTime) -> AmbiguousOffset {
self.tzif.to_ambiguous_kind(dt)
}
#[inline]
fn previous_transition(
&self,
timestamp: Timestamp,
) -> Option<TimeZoneTransition> {
self.tzif.previous_transition(timestamp)
}
#[inline]
fn next_transition(
&self,
timestamp: Timestamp,
) -> Option<TimeZoneTransition> {
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.
#[cfg(feature = "alloc")]
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()
}
}
/// A representation a single time zone transition.
///
/// A time zone transition is an instant in time the marks the beginning of
/// a change in the offset from UTC that civil time is computed from in a
/// particular time zone. For example, when daylight saving time comes into
/// effect (or goes away). Another example is when a geographic region changes
/// its permanent offset from UTC.
///
/// This is a low level type that you generally shouldn't need. It's useful in
/// cases where you need to know something about the specific instants at which
/// time zone transitions occur. For example, an embedded device might need to
/// be explicitly programmed with daylight saving time transitions. APIs like
/// this enable callers to explore those transitions.
///
/// This type is yielded by the iterators
/// [`TimeZonePrecedingTransitions`] and
/// [`TimeZoneFollowingTransitions`]. The iterators are created by
/// [`TimeZone::preceding`] and [`TimeZone::following`], respectively.
///
/// # Example
///
/// This shows a somewhat silly example that finds all of the unique civil
/// (or "clock" or "local") times at which a time zone transition has occurred
/// in a particular time zone:
///
/// ```
/// use std::collections::BTreeSet;
/// use jiff::{civil, tz::TimeZone};
///
/// let tz = TimeZone::get("America/New_York")?;
/// let now = civil::date(2024, 12, 31).at(18, 25, 0, 0).to_zoned(tz.clone())?;
/// let mut set = BTreeSet::new();
/// for trans in tz.preceding(now.timestamp()) {
/// let time = tz.to_datetime(trans.timestamp()).time();
/// set.insert(time);
/// }
/// assert_eq!(Vec::from_iter(set), vec![
/// civil::time(1, 0, 0, 0), // typical transition out of DST
/// civil::time(3, 0, 0, 0), // typical transition into DST
/// civil::time(12, 0, 0, 0), // from when IANA starts keeping track
/// civil::time(19, 0, 0, 0), // from World War 2
/// ]);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Debug)]
pub struct TimeZoneTransition<'t> {
// We don't currently do anything smart to make iterating over
// transitions faster. We could if we pushed the iterator impl down into
// the respective modules (`posix` and `tzif`), but it's not clear such
// optimization is really worth it. However, this API should permit that
// kind of optimization in the future.
timestamp: Timestamp,
offset: Offset,
abbrev: &'t str,
dst: Dst,
}
impl<'t> TimeZoneTransition<'t> {
/// Returns the timestamp at which this transition began.
///
/// # Example
///
/// ```
/// use jiff::{civil, tz::TimeZone};
///
/// let tz = TimeZone::get("US/Eastern")?;
/// // Look for the first time zone transition in `US/Eastern` following
/// // 2023-03-09 00:00:00.
/// let start = civil::date(2024, 3, 9).to_zoned(tz.clone())?.timestamp();
/// let next = tz.following(start).next().unwrap();
/// assert_eq!(
/// next.timestamp().to_zoned(tz.clone()).to_string(),
/// "2024-03-10T03:00:00-04:00[US/Eastern]",
/// );
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn timestamp(&self) -> Timestamp {
self.timestamp
}
/// Returns the offset corresponding to this time zone transition. All
/// instants at and following this transition's timestamp (and before the
/// next transition's timestamp) need to apply this offset from UTC to get
/// the civil or "local" time in the corresponding time zone.
///
/// # Example
///
/// ```
/// use jiff::{civil, tz::{TimeZone, offset}};
///
/// let tz = TimeZone::get("US/Eastern")?;
/// // Get the offset of the next transition after
/// // 2023-03-09 00:00:00.
/// let start = civil::date(2024, 3, 9).to_zoned(tz.clone())?.timestamp();
/// let next = tz.following(start).next().unwrap();
/// assert_eq!(next.offset(), offset(-4));
/// // Or go backwards to find the previous transition.
/// let prev = tz.preceding(start).next().unwrap();
/// assert_eq!(prev.offset(), offset(-5));
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn offset(&self) -> Offset {
self.offset
}
/// Returns the time zone abbreviation corresponding to this time
/// zone transition. All instants at and following this transition's
/// timestamp (and before the next transition's timestamp) may use this
/// abbreviation when creating a human readable string. For example,
/// this is the abbreviation used with the `%Z` specifier with Jiff's
/// [`fmt::strtime`](crate::fmt::strtime) module.
///
/// Note that abbreviations can to be ambiguous. For example, the
/// abbreviation `CST` can be used for the time zones `Asia/Shanghai`,
/// `America/Chicago` and `America/Havana`.
///
/// The lifetime of the string returned is tied to this
/// `TimeZoneTransition`, which may be shorter than `'t` (the lifetime of
/// the time zone this transition was created from).
///
/// # Example
///
/// ```
/// use jiff::{civil, tz::TimeZone};
///
/// let tz = TimeZone::get("US/Eastern")?;
/// // Get the abbreviation of the next transition after
/// // 2023-03-09 00:00:00.
/// let start = civil::date(2024, 3, 9).to_zoned(tz.clone())?.timestamp();
/// let next = tz.following(start).next().unwrap();
/// assert_eq!(next.abbreviation(), "EDT");
/// // Or go backwards to find the previous transition.
/// let prev = tz.preceding(start).next().unwrap();
/// assert_eq!(prev.abbreviation(), "EST");
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn abbreviation<'a>(&'a self) -> &'a str {
self.abbrev
}
/// Returns whether daylight saving time is enabled for this time zone
/// transition.
///
/// Callers should generally treat this as informational only. In
/// particular, not all time zone transitions are related to daylight
/// saving time. For example, some transitions are a result of a region
/// permanently changing their offset from UTC.
///
/// # Example
///
/// ```
/// use jiff::{civil, tz::{Dst, TimeZone}};
///
/// let tz = TimeZone::get("US/Eastern")?;
/// // Get the DST status of the next transition after
/// // 2023-03-09 00:00:00.
/// let start = civil::date(2024, 3, 9).to_zoned(tz.clone())?.timestamp();
/// let next = tz.following(start).next().unwrap();
/// assert_eq!(next.dst(), Dst::Yes);
/// // Or go backwards to find the previous transition.
/// let prev = tz.preceding(start).next().unwrap();
/// assert_eq!(prev.dst(), Dst::No);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn dst(&self) -> Dst {
self.dst
}
}
/// An iterator over time zone transitions going backward in time.
///
/// This iterator is created by [`TimeZone::preceding`].
///
/// # Example: show the 5 previous time zone transitions
///
/// This shows how to find the 5 preceding time zone transitions (from a
/// particular datetime) for a particular time zone:
///
/// ```
/// use jiff::{tz::offset, Zoned};
///
/// let now: Zoned = "2024-12-31 18:25-05[US/Eastern]".parse()?;
/// let transitions = now
/// .time_zone()
/// .preceding(now.timestamp())
/// .take(5)
/// .map(|t| (
/// t.timestamp().to_zoned(now.time_zone().clone()),
/// t.offset(),
/// t.abbreviation().to_string(),
/// ))
/// .collect::<Vec<_>>();
/// assert_eq!(transitions, vec![
/// ("2024-11-03 01:00-05[US/Eastern]".parse()?, offset(-5), "EST".to_string()),
/// ("2024-03-10 03:00-04[US/Eastern]".parse()?, offset(-4), "EDT".to_string()),
/// ("2023-11-05 01:00-05[US/Eastern]".parse()?, offset(-5), "EST".to_string()),
/// ("2023-03-12 03:00-04[US/Eastern]".parse()?, offset(-4), "EDT".to_string()),
/// ("2022-11-06 01:00-05[US/Eastern]".parse()?, offset(-5), "EST".to_string()),
/// ]);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Debug)]
pub struct TimeZonePrecedingTransitions<'t> {
tz: &'t TimeZone,
cur: Timestamp,
}
impl<'t> Iterator for TimeZonePrecedingTransitions<'t> {
type Item = TimeZoneTransition<'t>;
fn next(&mut self) -> Option<TimeZoneTransition<'t>> {
let trans = self.tz.previous_transition(self.cur)?;
self.cur = trans.timestamp();
Some(trans)
}
}
impl<'t> core::iter::FusedIterator for TimeZonePrecedingTransitions<'t> {}
/// An iterator over time zone transitions going forward in time.
///
/// This iterator is created by [`TimeZone::following`].
///
/// # Example: show the 5 next time zone transitions
///
/// This shows how to find the 5 following time zone transitions (from a
/// particular datetime) for a particular time zone:
///
/// ```
/// use jiff::{tz::offset, Zoned};
///
/// let now: Zoned = "2024-12-31 18:25-05[US/Eastern]".parse()?;
/// let transitions = now
/// .time_zone()
/// .following(now.timestamp())
/// .take(5)
/// .map(|t| (
/// t.timestamp().to_zoned(now.time_zone().clone()),
/// t.offset(),
/// t.abbreviation().to_string(),
/// ))
/// .collect::<Vec<_>>();
/// assert_eq!(transitions, vec![
/// ("2025-03-09 03:00-04[US/Eastern]".parse()?, offset(-4), "EDT".to_string()),
/// ("2025-11-02 01:00-05[US/Eastern]".parse()?, offset(-5), "EST".to_string()),
/// ("2026-03-08 03:00-04[US/Eastern]".parse()?, offset(-4), "EDT".to_string()),
/// ("2026-11-01 01:00-05[US/Eastern]".parse()?, offset(-5), "EST".to_string()),
/// ("2027-03-14 03:00-04[US/Eastern]".parse()?, offset(-4), "EDT".to_string()),
/// ]);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Debug)]
pub struct TimeZoneFollowingTransitions<'t> {
tz: &'t TimeZone,
cur: Timestamp,
}
impl<'t> Iterator for TimeZoneFollowingTransitions<'t> {
type Item = TimeZoneTransition<'t>;
fn next(&mut self) -> Option<TimeZoneTransition<'t>> {
let trans = self.tz.next_transition(self.cur)?;
self.cur = trans.timestamp();
Some(trans)
}
}
impl<'t> core::iter::FusedIterator for TimeZoneFollowingTransitions<'t> {}
/// A helper type for converting a `TimeZone` to a succinct human readable
/// description.
///
/// This is principally used in error messages in various places.
///
/// A previous iteration of this was just an `as_str() -> &str` method on
/// `TimeZone`, but that's difficult to do without relying on dynamic memory
/// allocation (or chunky arrays).
pub(crate) struct DiagnosticName<'a>(&'a TimeZone);
impl<'a> core::fmt::Display for DiagnosticName<'a> {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
let Some(ref kind) = self.0.kind else { return write!(f, "UTC") };
match **kind {
TimeZoneKind::Unknown => write!(f, "Etc/Unknown"),
TimeZoneKind::Fixed(ref tz) => write!(f, "{tz}"),
#[cfg(feature = "alloc")]
TimeZoneKind::Posix(ref tz) => write!(f, "{tz}"),
#[cfg(feature = "alloc")]
TimeZoneKind::Tzif(ref tz) => {
write!(f, "{}", tz.name().unwrap_or("Local"))
}
}
}
}
/// 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(),
}
}
}
/// An offset along with DST status and a time zone abbreviation.
///
/// This information can be computed from a [`TimeZone`] given a [`Timestamp`]
/// via [`TimeZone::to_offset_info`].
///
/// Generally, the extra information associated with the offset is not commonly
/// needed. And indeed, inspecting the daylight saving time status of a
/// particular instant in a time zone _usually_ leads to bugs. For example, not
/// all time zone transitions are the result of daylight saving time. Some are
/// the result of permanent changes to the standard UTC offset of a region.
///
/// This information is available via an API distinct from
/// [`TimeZone::to_offset`] because it is not commonly needed and because it
/// can sometimes be more expensive to compute.
///
/// The main use case for daylight saving time status or time zone
/// abbreviations is for formatting datetimes in an end user's locale. If you
/// want this, consider using the [`icu`] crate via [`jiff-icu`].
///
/// The lifetime parameter `'t` corresponds to the lifetime of the `TimeZone`
/// that this info was extracted from.
///
/// # 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 info = tz.to_offset_info(ts);
/// assert_eq!(info.offset(), tz::offset(-4));
/// assert_eq!(info.dst(), Dst::Yes);
/// assert_eq!(info.abbreviation(), "EDT");
/// assert_eq!(
/// info.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 info = tz.to_offset_info(ts);
/// assert_eq!(info.offset(), tz::offset(-5));
/// assert_eq!(info.dst(), Dst::No);
/// assert_eq!(info.abbreviation(), "EST");
/// assert_eq!(
/// info.offset().to_datetime(ts).to_string(),
/// "2024-01-10T21:46:44",
/// );
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// [`icu`]: https://docs.rs/icu
/// [`jiff-icu`]: https://docs.rs/jiff-icu
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct TimeZoneOffsetInfo<'t> {
offset: Offset,
dst: Dst,
abbreviation: TimeZoneAbbreviation<'t>,
}
impl<'t> TimeZoneOffsetInfo<'t> {
/// Returns the offset.
///
/// The offset is duration, from UTC, that should be used to offset the
/// civil time in a particular location.
///
/// # Example
///
/// ```
/// use jiff::{civil, tz::{TimeZone, offset}};
///
/// let tz = TimeZone::get("US/Eastern")?;
/// // Get the offset for 2023-03-10 00:00:00.
/// let start = civil::date(2024, 3, 10).to_zoned(tz.clone())?.timestamp();
/// let info = tz.to_offset_info(start);
/// assert_eq!(info.offset(), offset(-5));
/// // Go forward a day and notice the offset changes due to DST!
/// let start = civil::date(2024, 3, 11).to_zoned(tz.clone())?.timestamp();
/// let info = tz.to_offset_info(start);
/// assert_eq!(info.offset(), offset(-4));
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn offset(&self) -> Offset {
self.offset
}
/// Returns the time zone abbreviation corresponding to this offset info.
///
/// Note that abbreviations can to be ambiguous. For example, the
/// abbreviation `CST` can be used for the time zones `Asia/Shanghai`,
/// `America/Chicago` and `America/Havana`.
///
/// The lifetime of the string returned is tied to this
/// `TimeZoneOffsetInfo`, which may be shorter than `'t` (the lifetime of
/// the time zone this transition was created from).
///
/// # Example
///
/// ```
/// use jiff::{civil, tz::TimeZone};
///
/// let tz = TimeZone::get("US/Eastern")?;
/// // Get the time zone abbreviation for 2023-03-10 00:00:00.
/// let start = civil::date(2024, 3, 10).to_zoned(tz.clone())?.timestamp();
/// let info = tz.to_offset_info(start);
/// assert_eq!(info.abbreviation(), "EST");
/// // Go forward a day and notice the abbreviation changes due to DST!
/// let start = civil::date(2024, 3, 11).to_zoned(tz.clone())?.timestamp();
/// let info = tz.to_offset_info(start);
/// assert_eq!(info.abbreviation(), "EDT");
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn abbreviation(&self) -> &str {
self.abbreviation.as_str()
}
/// Returns whether daylight saving time is enabled for this offset
/// info.
///
/// Callers should generally treat this as informational only. In
/// particular, not all time zone transitions are related to daylight
/// saving time. For example, some transitions are a result of a region
/// permanently changing their offset from UTC.
///
/// # Example
///
/// ```
/// use jiff::{civil, tz::{Dst, TimeZone}};
///
/// let tz = TimeZone::get("US/Eastern")?;
/// // Get the DST status of 2023-03-11 00:00:00.
/// let start = civil::date(2024, 3, 11).to_zoned(tz.clone())?.timestamp();
/// let info = tz.to_offset_info(start);
/// assert_eq!(info.dst(), Dst::Yes);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn dst(&self) -> Dst {
self.dst
}
}
/// A light abstraction over different representations of a time zone
/// abbreviation.
///
/// The lifetime parameter `'t` corresponds to the lifetime of the time zone
/// that produced this abbreviation.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
enum TimeZoneAbbreviation<'t> {
/// For when the abbreviation is borrowed directly from other data. For
/// example, from TZif or from POSIX TZ strings.
Borrowed(&'t str),
/// For when the abbreviation has to be derived from other data. For
/// example, from a fixed offset.
///
/// The idea here is that a `TimeZone` shouldn't need to store the
/// string representation of a fixed offset. Particularly in core-only
/// environments, this is quite wasteful. So we make the string on-demand
/// only when it's requested.
///
/// An alternative design is to just implement `Display` and reuse
/// `Offset`'s `Display` impl, but then we couldn't offer a `-> &str` API.
/// I feel like that's just a bit overkill, and really just comes from the
/// core-only straight-jacket.
Owned(ArrayStr<9>),
}
impl<'t> TimeZoneAbbreviation<'t> {
/// Returns this abbreviation as a string borrowed from `self`.
///
/// Notice that, like `Cow`, the lifetime of the string returned is
/// tied to `self` and thus may be shorter than `'t`.
fn as_str<'a>(&'a self) -> &'a str {
match *self {
TimeZoneAbbreviation::Borrowed(s) => s,
TimeZoneAbbreviation::Owned(ref s) => s.as_str(),
}
}
}
/// 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;
#[cfg(feature = "alloc")]
use crate::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 }
}
#[cfg(feature = "alloc")]
#[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}",
);
}
}
}
#[cfg(feature = "alloc")]
#[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 info = tz.to_offset_info(timestamp);
assert_eq!(
info.offset(),
offset,
"\nTZ={tzname}, timestamp({unix_sec}, {unix_nano})",
);
assert_eq!(
info.abbreviation(),
abbrev,
"\nTZ={tzname}, timestamp({unix_sec}, {unix_nano})",
);
assert_eq!(
info.offset().to_datetime(timestamp),
date(year, month, day).at(hour, min, sec, nano),
"\nTZ={tzname}, timestamp({unix_sec}, {unix_nano})",
);
}
}
}
#[cfg(feature = "alloc")]
#[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}",
);
}
}
}
#[cfg(feature = "alloc")]
#[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),
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());
}
#[cfg(feature = "alloc")]
#[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).map(|t| t.timestamp());
assert_eq!(got, expected, "\nTZ: {tzname}\ngiven: {given}");
}
}
}
#[cfg(feature = "alloc")]
#[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).map(|t| t.timestamp());
assert_eq!(got, expected, "\nTZ: {tzname}\ngiven: {given}");
}
}
}
#[cfg(feature = "alloc")]
#[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).map(|t| t.timestamp());
assert_eq!(got, expected, "\nTZ: {posix_tz}\ngiven: {given}");
}
}
}
#[cfg(feature = "alloc")]
#[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).map(|t| t.timestamp());
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() {
#[cfg(feature = "alloc")]
{
let word = core::mem::size_of::<usize>();
assert_eq!(word, core::mem::size_of::<TimeZone>());
}
#[cfg(all(target_pointer_width = "64", not(feature = "alloc")))]
{
#[cfg(debug_assertions)]
{
assert_eq!(16, core::mem::size_of::<TimeZone>());
}
#[cfg(not(debug_assertions))]
{
// This asserts the same value as the alloc value above, but
// it wasn't always this way, which is why it's written out
// separately. Moreover, in theory, I'd be open to regressing
// this value if it led to an improvement in alloc-mode. But
// more likely, it would be nice to decrease this size in
// non-alloc modes.
assert_eq!(8, core::mem::size_of::<TimeZone>());
}
}
}
/// This tests a few other cases for `TimeZone::to_offset` that
/// probably aren't worth showing in doctest examples.
#[test]
fn time_zone_to_offset() {
let ts = Timestamp::from_second(123456789).unwrap();
let tz = TimeZone::fixed(offset(-5));
let info = tz.to_offset_info(ts);
assert_eq!(info.offset(), offset(-5));
assert_eq!(info.dst(), Dst::No);
assert_eq!(info.abbreviation(), "-05");
let tz = TimeZone::fixed(offset(5));
let info = tz.to_offset_info(ts);
assert_eq!(info.offset(), offset(5));
assert_eq!(info.dst(), Dst::No);
assert_eq!(info.abbreviation(), "+05");
let tz = TimeZone::fixed(offset(-12));
let info = tz.to_offset_info(ts);
assert_eq!(info.offset(), offset(-12));
assert_eq!(info.dst(), Dst::No);
assert_eq!(info.abbreviation(), "-12");
let tz = TimeZone::fixed(offset(12));
let info = tz.to_offset_info(ts);
assert_eq!(info.offset(), offset(12));
assert_eq!(info.dst(), Dst::No);
assert_eq!(info.abbreviation(), "+12");
let tz = TimeZone::fixed(offset(0));
let info = tz.to_offset_info(ts);
assert_eq!(info.offset(), offset(0));
assert_eq!(info.dst(), Dst::No);
assert_eq!(info.abbreviation(), "UTC");
}
/// This tests a few other cases for `TimeZone::to_fixed_offset` that
/// probably aren't worth showing in doctest examples.
#[test]
fn time_zone_to_fixed_offset() {
let tz = TimeZone::UTC;
assert_eq!(tz.to_fixed_offset().unwrap(), Offset::UTC);
let offset = Offset::from_hours(1).unwrap();
let tz = TimeZone::fixed(offset);
assert_eq!(tz.to_fixed_offset().unwrap(), offset);
#[cfg(feature = "alloc")]
{
let tz = TimeZone::posix("EST5").unwrap();
assert!(tz.to_fixed_offset().is_err());
let test_file = TzifTestFile::get("America/New_York");
let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
assert!(tz.to_fixed_offset().is_err());
}
}
}