dtt/datetime.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
// datetime.rs
//
// Copyright © 2025 DateTime (DTT) library.
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! DateTime module for managing dates, times, and timezones in Rust.
//!
//! # Overview
//!
//! This module provides a comprehensive datetime manipulation API that includes:
//! - Fixed offset timezone support
//! - Date and time creation and parsing
//! - Format conversion (RFC 3339, ISO 8601)
//! - Date arithmetic and comparison operations
//! - Validation utilities
//!
//! **Note**: Daylight Saving Time (DST) is **not automatically handled**. Users must
//! manually manage DST transitions by selecting appropriate timezone offsets.
//!
//! # Examples
//!
//! ```rust
//! use dtt::datetime::DateTime;
//!
//! // Create current UTC time
//! let now = DateTime::new();
//!
//! // Parse specific datetime
//! let maybe_dt = DateTime::parse("2024-01-01T12:00:00Z");
//! if let Ok(dt) = maybe_dt {
//! // Convert timezone
//! let est = dt.convert_to_tz("EST");
//! if let Ok(est_dt) = est {
//! // ...
//! }
//! }
//! ```
#![deny(
missing_docs,
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::result_unit_err,
clippy::clone_on_ref_ptr
)]
#![warn(clippy::pedantic, clippy::nursery, clippy::cargo)]
use crate::error::DateTimeError;
use serde::{Deserialize, Serialize};
use std::{
cmp::Ordering,
collections::HashMap,
fmt,
hash::{Hash, Hasher},
ops::{Add, Sub},
str::FromStr,
};
use time::{
format_description, Date, Duration, Month, OffsetDateTime,
PrimitiveDateTime, Time, UtcOffset, Weekday,
};
/// Maximum valid hour value (0-23)
const MAX_HOUR: u8 = 23;
/// Maximum valid minute/second value (0-59)
const MAX_MIN_SEC: u8 = 59;
/// Maximum valid day value (1-31)
const MAX_DAY: u8 = 31;
/// Maximum valid month value (1-12)
const MAX_MONTH: u8 = 12;
/// Maximum valid microsecond value (0-999_999)
const MAX_MICROSECOND: u32 = 999_999;
/// Maximum valid ISO week number (1-53)
const MAX_ISO_WEEK: u8 = 53;
/// Maximum valid ordinal day (1-366)
const MAX_ORDINAL_DAY: u16 = 366;
/// Represents a date and time with timezone offset support.
///
/// This struct combines a UTC datetime with a timezone offset, allowing for
/// timezone-aware datetime operations. While it supports fixed offsets,
/// it does **not** automatically handle DST transitions.
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
///
/// let utc = DateTime::new();
/// let maybe_est = utc.convert_to_tz("EST");
/// if let Ok(est) = maybe_est {
/// // ...
/// }
/// ```
#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct DateTime {
/// The date and time in UTC (when offset = `UtcOffset::UTC`) or a
/// user-chosen offset if `offset != UtcOffset::UTC`.
pub datetime: PrimitiveDateTime,
/// The timezone offset from UTC.
pub offset: UtcOffset,
}
lazy_static::lazy_static! {
/// Static mapping of timezone abbreviations to their `UtcOffset`.
///
/// # Note
///
/// This is not an exhaustive list of timezones. It is a convenient subset
/// for demonstration purposes. Real-world usage might integrate a
/// more robust timezone library or database.
static ref TIMEZONE_OFFSETS: HashMap<&'static str, Result<UtcOffset, DateTimeError>> = {
let mut m = HashMap::new();
let _ = m.insert("UTC", Ok(UtcOffset::UTC));
let _ = m.insert("GMT", Ok(UtcOffset::UTC));
// North American time zones
let _ = m.insert("EST", UtcOffset::from_hms(-5, 0, 0).map_err(DateTimeError::from));
let _ = m.insert("EDT", UtcOffset::from_hms(-4, 0, 0).map_err(DateTimeError::from));
let _ = m.insert("CST", UtcOffset::from_hms(-6, 0, 0).map_err(DateTimeError::from));
let _ = m.insert("CDT", UtcOffset::from_hms(-5, 0, 0).map_err(DateTimeError::from));
let _ = m.insert("MST", UtcOffset::from_hms(-7, 0, 0).map_err(DateTimeError::from));
let _ = m.insert("MDT", UtcOffset::from_hms(-6, 0, 0).map_err(DateTimeError::from));
let _ = m.insert("PST", UtcOffset::from_hms(-8, 0, 0).map_err(DateTimeError::from));
let _ = m.insert("PDT", UtcOffset::from_hms(-7, 0, 0).map_err(DateTimeError::from));
// European time zones
let _ = m.insert("CET", UtcOffset::from_hms(1, 0, 0).map_err(DateTimeError::from));
let _ = m.insert("CEST", UtcOffset::from_hms(2, 0, 0).map_err(DateTimeError::from));
let _ = m.insert("EET", UtcOffset::from_hms(2, 0, 0).map_err(DateTimeError::from));
let _ = m.insert("EEST", UtcOffset::from_hms(3, 0, 0).map_err(DateTimeError::from));
// Asian time zones
let _ = m.insert("JST", UtcOffset::from_hms(9, 0, 0).map_err(DateTimeError::from));
let _ = m.insert("IST", UtcOffset::from_hms(5, 30, 0).map_err(DateTimeError::from));
let _ = m.insert("HKT", UtcOffset::from_hms(8, 0, 0).map_err(DateTimeError::from));
// Australian time zones
let _ = m.insert("AEDT", UtcOffset::from_hms(11, 0, 0).map_err(DateTimeError::from));
let _ = m.insert("AEST", UtcOffset::from_hms(10, 0, 0).map_err(DateTimeError::from));
let _ = m.insert(
"WADT",
UtcOffset::from_hms(8, 45, 0)
.map_err(DateTimeError::from)
);
m
};
}
// -----------------------------------------------------------------------------
// Builder Pattern
// -----------------------------------------------------------------------------
/// A builder for [`DateTime`] objects, allowing more ergonomic creation of
/// datetimes with customized year, month, day, hour, minute, second, and offset.
///
/// # Examples
///
/// ```
/// use dtt::datetime::{DateTime, DateTimeBuilder};
/// use time::UtcOffset;
///
/// let builder = DateTimeBuilder::new()
/// .year(2024)
/// .month(1)
/// .day(1)
/// .hour(12)
/// .minute(30)
/// .second(45)
/// .offset(UtcOffset::UTC);
///
/// let dt = builder.build();
/// assert!(dt.is_ok());
///
/// let dt_unwrapped = dt.unwrap();
/// assert_eq!(dt_unwrapped.year(), 2024);
/// assert_eq!(dt_unwrapped.month().to_string(), "January");
/// assert_eq!(dt_unwrapped.day(), 1);
/// assert_eq!(dt_unwrapped.hour(), 12);
/// assert_eq!(dt_unwrapped.minute(), 30);
/// assert_eq!(dt_unwrapped.second(), 45);
/// assert_eq!(dt_unwrapped.offset(), UtcOffset::UTC);
/// ```
#[derive(
Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize,
)]
pub struct DateTimeBuilder {
/// Calendar year, e.g. 2024.
year: i32,
/// Month (1-12).
month: u8,
/// Day of the month (1-31, depends on month).
day: u8,
/// Hour of the day (0-23).
hour: u8,
/// Minute of the hour (0-59).
minute: u8,
/// Second of the minute (0-59).
second: u8,
/// The time zone offset from UTC.
offset: UtcOffset,
}
impl Default for DateTimeBuilder {
fn default() -> Self {
Self {
year: 1970,
month: 1,
day: 1,
hour: 0,
minute: 0,
second: 0,
offset: UtcOffset::UTC,
}
}
}
impl DateTimeBuilder {
/// Creates a new `DateTimeBuilder` with default values set to
/// midnight, January 1, 1970 (UTC).
#[must_use]
pub const fn new() -> Self {
Self {
year: 1970,
month: 1,
day: 1,
hour: 0,
minute: 0,
second: 0,
offset: UtcOffset::UTC,
}
}
/// Sets the year component.
#[must_use]
pub const fn year(mut self, year: i32) -> Self {
self.year = year;
self
}
/// Sets the month component.
#[must_use]
pub const fn month(mut self, month: u8) -> Self {
self.month = month;
self
}
/// Sets the day component.
#[must_use]
pub const fn day(mut self, day: u8) -> Self {
self.day = day;
self
}
/// Sets the hour component.
#[must_use]
pub const fn hour(mut self, hour: u8) -> Self {
self.hour = hour;
self
}
/// Sets the minute component.
#[must_use]
pub const fn minute(mut self, minute: u8) -> Self {
self.minute = minute;
self
}
/// Sets the second component.
#[must_use]
pub const fn second(mut self, second: u8) -> Self {
self.second = second;
self
}
/// Sets the time zone offset component.
#[must_use]
pub const fn offset(mut self, offset: UtcOffset) -> Self {
self.offset = offset;
self
}
/// Builds the final [`DateTime`] from the builder state.
///
/// # Errors
///
/// Returns a `DateTimeError` if any of the date components are invalid
/// (e.g., `month = 13` or `day = 32`).
pub fn build(&self) -> Result<DateTime, DateTimeError> {
DateTime::from_components(
self.year,
self.month,
self.day,
self.hour,
self.minute,
self.second,
self.offset,
)
}
}
// -----------------------------------------------------------------------------
// Core Implementations
// -----------------------------------------------------------------------------
impl DateTime {
// -------------------------------------------------------------------------
// Creation Methods
// -------------------------------------------------------------------------
/// Creates a new `DateTime` instance representing the current UTC time.
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
///
/// let now = DateTime::new();
/// ```
#[must_use]
pub fn new() -> Self {
// Directly obtain the current UTC time.
let now = OffsetDateTime::now_utc();
Self {
datetime: PrimitiveDateTime::new(now.date(), now.time()),
offset: UtcOffset::UTC,
}
}
/// Creates a new `DateTime` instance with the current time in the specified timezone.
///
/// # Arguments
///
/// * `tz` - A timezone abbreviation (e.g., "UTC", "EST", "PST")
///
/// # Returns
///
/// Returns a `Result` containing either the new `DateTime` instance or a `DateTimeError`
/// if the timezone is invalid.
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
///
/// let maybe_est_time = DateTime::new_with_tz("EST");
/// if let Ok(est_time) = maybe_est_time {
/// // ...
/// }
/// ```
///
/// # Errors
///
/// Returns a `DateTimeError` if the timezone is invalid.
///
pub fn new_with_tz(tz: &str) -> Result<Self, DateTimeError> {
let offset = TIMEZONE_OFFSETS
.get(tz)
.ok_or(DateTimeError::InvalidTimezone)?
.as_ref()
.map_err(Clone::clone)?;
let now_utc = OffsetDateTime::now_utc();
let now_local = now_utc.to_offset(*offset);
Ok(Self {
datetime: PrimitiveDateTime::new(
now_local.date(),
now_local.time(),
),
offset: *offset,
})
}
/// Creates a new `DateTime` instance with a custom UTC offset.
///
/// # Arguments
///
/// * `hours` - Hour offset from UTC (-23 to +23)
/// * `minutes` - Minute offset from UTC (-59 to +59)
///
/// # Returns
///
/// Returns a `Result` containing either the new `DateTime` or a `DateTimeError`
/// if the offset is invalid.
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
///
/// // Create time with UTC+5:30 offset (e.g., for India)
/// let maybe_ist = DateTime::new_with_custom_offset(5, 30);
/// if let Ok(ist) = maybe_ist {
/// // ...
/// }
/// ```
///
/// # Errors
///
/// Returns a `DateTimeError` if the timezone is invalid.
///
pub fn new_with_custom_offset(
hours: i8,
minutes: i8,
) -> Result<Self, DateTimeError> {
// Direct numeric checks (no casts needed)
if hours.abs() > 23 || minutes.abs() > 59 {
return Err(DateTimeError::InvalidTimezone);
}
let offset = UtcOffset::from_hms(hours, minutes, 0)
.map_err(|_| DateTimeError::InvalidTimezone)?;
let now_utc = OffsetDateTime::now_utc();
let now_local = now_utc.to_offset(offset);
Ok(Self {
datetime: PrimitiveDateTime::new(
now_local.date(),
now_local.time(),
),
offset,
})
}
/// Returns a new `DateTime` which is exactly one day earlier.
///
/// # Returns
///
/// Returns a `Result` containing the new `DateTime` or a `DateTimeError`
/// if subtracting one day would result in an invalid date.
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
///
/// let now = DateTime::new();
/// let maybe_yesterday = now.previous_day();
/// assert!(maybe_yesterday.is_ok());
/// ```
///
/// # Errors
///
/// Returns a `DateTimeError` if the resulting date would be invalid.
///
pub fn previous_day(&self) -> Result<Self, DateTimeError> {
self.add_days(-1)
}
/// Returns a new `DateTime` which is exactly one day later.
///
/// # Returns
///
/// Returns a `Result` containing the new `DateTime` or a `DateTimeError`
/// if adding one day would result in an invalid date.
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
///
/// let now = DateTime::new();
/// let maybe_tomorrow = now.next_day();
/// assert!(maybe_tomorrow.is_ok());
/// ```
///
/// # Errors
///
/// Returns a `DateTimeError` if the resulting date would be invalid.
///
pub fn next_day(&self) -> Result<Self, DateTimeError> {
self.add_days(1)
}
/// Sets the time components (hour, minute, second) while preserving the current date
/// and timezone offset.
///
/// # Arguments
///
/// * `hour` - Hour (0-23)
/// * `minute` - Minute (0-59)
/// * `second` - Second (0-59)
///
/// # Returns
///
/// Returns a `Result` containing either the new `DateTime` or a `DateTimeError`
/// if the time components are invalid.
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
///
/// let dt = DateTime::new();
/// // Attempt to set the time to 10:30:45
/// let updated_dt = dt.set_time(10, 30, 45);
/// assert!(updated_dt.is_ok());
/// if let Ok(new_val) = updated_dt {
/// assert_eq!(new_val.hour(), 10);
/// assert_eq!(new_val.minute(), 30);
/// assert_eq!(new_val.second(), 45);
/// }
/// ```
///
/// # Errors
///
/// Returns a `DateTimeError` if the resulting time would be invalid.
///
pub fn set_time(
&self,
hour: u8,
minute: u8,
second: u8,
) -> Result<Self, DateTimeError> {
// Construct a new time; returns an error if invalid
let new_time = Time::from_hms(hour, minute, second)
.map_err(|_| DateTimeError::InvalidTime)?;
// Preserve the existing date
Ok(Self {
datetime: PrimitiveDateTime::new(
self.datetime.date(),
new_time,
),
offset: self.offset,
})
}
/// Subtracts a specified number of years from the `DateTime`.
///
/// Handles leap year transitions appropriately (e.g., if subtracting a year from
/// Feb 29 results in Feb 28).
///
/// # Arguments
///
/// * `years` - Number of years to subtract
///
/// # Returns
///
/// Returns a `Result` containing either the new `DateTime` or a `DateTimeError`
/// if the resulting date would be invalid.
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
///
/// let dt = DateTime::new();
/// let maybe_past = dt.sub_years(1);
/// assert!(maybe_past.is_ok());
/// ```
///
/// # Errors
///
/// Returns a `DateTimeError` if the resulting date would be invalid.
///
pub fn sub_years(&self, years: i32) -> Result<Self, DateTimeError> {
self.add_years(-years)
}
/// Converts this `DateTime` to another timezone, then formats it
/// using the provided `format_str`.
///
/// # Arguments
///
/// * `tz` - Target timezone abbreviation (e.g., "UTC", "EST", "PST").
/// * `format_str` - A format description (see the `time` crate documentation
/// for the supported syntax).
///
/// # Returns
///
/// Returns a `Result<String, DateTimeError>` containing either
/// the formatted datetime string or an error if conversion or
/// formatting fails.
///
/// # Errors
///
/// This function will return a [`DateTimeError`] if:
/// - The specified timezone is not recognized or invalid.
/// - The formatting operation fails due to an invalid `format_str`.
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
///
/// let dt = DateTime::new();
/// let result = dt.format_time_in_timezone("EST", "[hour]:[minute]:[second]");
/// if let Ok(formatted_str) = result {
/// println!("Time in EST: {}", formatted_str);
/// }
/// ```
pub fn format_time_in_timezone(
&self,
tz: &str,
format_str: &str,
) -> Result<String, DateTimeError> {
// 1. Convert this DateTime to the specified timezone
let dt_tz = self.convert_to_tz(tz)?;
// 2. Format the timezone-adjusted DateTime using the provided format string
dt_tz.format(format_str)
}
/// Returns `true` if the input string is a valid ISO 8601 or RFC 3339–like datetime/date.
///
/// # Arguments
///
/// * `input` - A string that might represent a date or datetime in ISO 8601/RFC 3339 format.
///
/// # Returns
///
/// `true` if the string can be successfully parsed as either:
/// - RFC 3339 datetime (e.g., "2024-01-01T12:00:00Z"), or
/// - ISO 8601 date (e.g., "2024-01-01")
/// `false` otherwise.
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
///
/// assert!(DateTime::is_valid_iso_8601("2024-01-01T12:00:00Z"));
/// assert!(DateTime::is_valid_iso_8601("2024-01-01"));
/// assert!(!DateTime::is_valid_iso_8601("2024-13-01")); // invalid month
/// assert!(!DateTime::is_valid_iso_8601("not a date"));
/// ```
#[must_use]
pub fn is_valid_iso_8601(input: &str) -> bool {
// 1. Try parsing the string as RFC 3339 (a strict subset of ISO 8601).
if PrimitiveDateTime::parse(
input,
&format_description::well_known::Rfc3339,
)
.is_ok()
{
return true;
}
// 2. Otherwise, try parsing as just the date portion of ISO 8601 (yyyy-mm-dd).
if Date::parse(
input,
&format_description::well_known::Iso8601::DATE,
)
.is_ok()
{
return true;
}
// 3. If both attempts fail, it's not a valid ISO 8601 or RFC 3339 datetime/date.
false
}
/// Creates a `DateTime` instance from individual components.
///
/// # Arguments
///
/// * `year` - Calendar year
/// * `month` - Month (1-12)
/// * `day` - Day of month (1-31, depending on month)
/// * `hour` - Hour (0-23)
/// * `minute` - Minute (0-59)
/// * `second` - Second (0-59)
/// * `offset` - Timezone offset from UTC
///
/// # Returns
///
/// Returns a `Result` containing either the new `DateTime` or a `DateTimeError`
/// if any component is invalid.
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
/// use time::UtcOffset;
///
/// let dt = DateTime::from_components(2024, 1, 1, 12, 0, 0, UtcOffset::UTC);
/// assert!(dt.is_ok());
/// ```
///
/// # Errors
///
/// Returns a `DateTimeError` if any component is invalid.
///
pub fn from_components(
year: i32,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
offset: UtcOffset,
) -> Result<Self, DateTimeError> {
let month = Month::try_from(month)
.map_err(|_| DateTimeError::InvalidDate)?;
let date = Date::from_calendar_date(year, month, day)
.map_err(|_| DateTimeError::InvalidDate)?;
let time = Time::from_hms(hour, minute, second)
.map_err(|_| DateTimeError::InvalidTime)?;
Ok(Self {
datetime: PrimitiveDateTime::new(date, time),
offset,
})
}
// -------------------------------------------------------------------------
// Getter Methods
// -------------------------------------------------------------------------
/// Returns the year component of the `DateTime`.
#[must_use]
pub const fn year(&self) -> i32 {
self.datetime.date().year()
}
/// Returns the month component of the `DateTime`.
#[must_use]
pub const fn month(&self) -> Month {
self.datetime.date().month()
}
/// Returns the day component of the `DateTime`.
#[must_use]
pub const fn day(&self) -> u8 {
self.datetime.date().day()
}
/// Returns the hour component of the `DateTime`.
#[must_use]
pub const fn hour(&self) -> u8 {
self.datetime.time().hour()
}
/// Returns the minute component of the `DateTime`.
#[must_use]
pub const fn minute(&self) -> u8 {
self.datetime.time().minute()
}
/// Returns the second component of the `DateTime`.
#[must_use]
pub const fn second(&self) -> u8 {
self.datetime.time().second()
}
/// Returns the microsecond component of the `DateTime`.
#[must_use]
pub const fn microsecond(&self) -> u32 {
self.datetime.microsecond()
}
/// Returns the ISO week component of the `DateTime`.
#[must_use]
pub const fn iso_week(&self) -> u8 {
self.datetime.iso_week()
}
/// Returns the ordinal day (day of year) component of the `DateTime`.
#[must_use]
pub const fn ordinal(&self) -> u16 {
self.datetime.ordinal()
}
/// Returns the timezone offset of the `DateTime`.
#[must_use]
pub const fn offset(&self) -> UtcOffset {
self.offset
}
/// Returns the weekday of the `DateTime`.
#[must_use]
pub const fn weekday(&self) -> Weekday {
self.datetime.date().weekday()
}
// -------------------------------------------------------------------------
// Parsing Methods
// -------------------------------------------------------------------------
/// Parses a string representation of a date and time.
///
/// Supports both RFC 3339 and ISO 8601 formats.
///
/// # Arguments
///
/// * `input` - A string slice containing the date/time to parse
///
/// # Returns
///
/// Returns a `Result` containing either the parsed `DateTime` or a `DateTimeError`
/// if parsing fails.
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
///
/// // Parse RFC 3339 format
/// let dt1 = DateTime::parse("2024-01-01T12:00:00Z");
///
/// // Parse ISO 8601 date
/// let dt2 = DateTime::parse("2024-01-01");
/// assert!(dt1.is_ok());
/// assert!(dt2.is_ok());
/// ```
///
/// # Errors
///
/// Returns a `DateTimeError` if the input string is not a valid date/time.
///
pub fn parse(input: &str) -> Result<Self, DateTimeError> {
// Try RFC 3339 format first
if let Ok(dt) = PrimitiveDateTime::parse(
input,
&format_description::well_known::Rfc3339,
) {
return Ok(Self {
datetime: dt,
offset: UtcOffset::UTC,
});
}
// Fall back to ISO 8601 date format
if let Ok(date) = Date::parse(
input,
&format_description::well_known::Iso8601::DATE,
) {
return Ok(Self {
datetime: PrimitiveDateTime::new(date, Time::MIDNIGHT),
offset: UtcOffset::UTC,
});
}
Err(DateTimeError::InvalidFormat)
}
/// Parses a date/time string using a custom format specification.
///
/// # Arguments
///
/// * `input` - The date/time string to parse
/// * `format` - Format specification string (see `time` crate documentation)
///
/// # Returns
///
/// Returns a `Result` containing either the parsed `DateTime` or a `DateTimeError`
/// if parsing fails.
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
///
/// let dt = DateTime::parse_custom_format(
/// "2024-01-01 12:00:00",
/// "[year]-[month]-[day] [hour]:[minute]:[second]"
/// );
/// assert!(dt.is_ok());
/// ```
///
/// # Errors
///
/// Returns a `DateTimeError` if the input string is not a valid date/time.
///
pub fn parse_custom_format(
input: &str,
format: &str,
) -> Result<Self, DateTimeError> {
let format_desc = format_description::parse(format)
.map_err(|_| DateTimeError::InvalidFormat)?;
let datetime = PrimitiveDateTime::parse(input, &format_desc)
.map_err(|_| DateTimeError::InvalidFormat)?;
Ok(Self {
datetime,
offset: UtcOffset::UTC,
})
}
// -------------------------------------------------------------------------
// Formatting Methods
// -------------------------------------------------------------------------
/// Formats the `DateTime` according to the specified format string.
///
/// # Arguments
///
/// * `format_str` - Format specification string (see `time` crate documentation)
///
/// # Returns
///
/// Returns a `Result` containing either the formatted string or a `DateTimeError`
/// if formatting fails.
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
///
/// let dt = DateTime::new();
/// let formatted = dt.format("[year]-[month]-[day]");
/// assert!(formatted.is_ok());
/// ```
///
/// # Errors
///
/// Returns a `DateTimeError` if the format string is invalid.
///
pub fn format(
&self,
format_str: &str,
) -> Result<String, DateTimeError> {
let format_desc = format_description::parse(format_str)
.map_err(|_| DateTimeError::InvalidFormat)?;
self.datetime
.format(&format_desc)
.map_err(|_| DateTimeError::InvalidFormat)
}
/// Formats the `DateTime` as an RFC 3339 string.
///
/// # Returns
///
/// Returns a `Result` containing either the formatted RFC 3339 string
/// or a `DateTimeError` if formatting fails.
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
///
/// let dt = DateTime::new();
/// let maybe_rfc3339 = dt.format_rfc3339();
/// assert!(maybe_rfc3339.is_ok());
/// ```
///
/// # Errors
///
/// Returns a `DateTimeError` if formatting fails.
///
pub fn format_rfc3339(&self) -> Result<String, DateTimeError> {
self.datetime
.assume_offset(self.offset)
.format(&format_description::well_known::Rfc3339)
.map_err(|_| DateTimeError::InvalidFormat)
}
/// Formats the `DateTime` as an ISO 8601 string (YYYY-MM-DDTHH:MM:SS).
///
/// # Returns
///
/// Returns a `Result` containing either the formatted ISO 8601 string
/// or a `DateTimeError` if formatting fails.
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
///
/// let dt = DateTime::new();
/// let maybe_iso8601 = dt.format_iso8601();
/// assert!(maybe_iso8601.is_ok());
/// ```
///
/// # Errors
///
/// Returns a `DateTimeError` if formatting fails.
///
pub fn format_iso8601(&self) -> Result<String, DateTimeError> {
self.format("[year]-[month]-[day]T[hour]:[minute]:[second]")
}
/// Updates the `DateTime` to the current time while preserving the timezone offset.
///
/// # Returns
///
/// Returns a `Result` containing either the updated `DateTime` or a `DateTimeError`
/// if the update fails.
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
/// use std::thread::sleep;
/// use std::time::Duration;
///
/// let dt = DateTime::new();
/// sleep(Duration::from_secs(1));
/// let updated_dt = dt.update();
/// assert!(updated_dt.is_ok());
/// ```
///
/// # Errors
///
/// Returns a `DateTimeError` if the update fails.
///
pub fn update(&self) -> Result<Self, DateTimeError> {
let now = OffsetDateTime::now_utc().to_offset(self.offset);
Ok(Self {
datetime: PrimitiveDateTime::new(now.date(), now.time()),
offset: self.offset,
})
}
// -------------------------------------------------------------------------
// Timezone Conversion Method
// -------------------------------------------------------------------------
/// Converts the current `DateTime` to another timezone.
///
/// # Arguments
///
/// * `new_tz` - Target timezone abbreviation (e.g., "UTC", "EST", "PST")
///
/// # Returns
///
/// Returns a `Result` containing either the `DateTime` in the new timezone
/// or a `DateTimeError` if the conversion fails.
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
///
/// let utc = DateTime::new();
/// let maybe_est = utc.convert_to_tz("EST");
/// assert!(maybe_est.is_ok());
/// ```
///
/// # Errors
///
/// Returns a `DateTimeError` if the timezone is invalid.
///
pub fn convert_to_tz(
&self,
new_tz: &str,
) -> Result<Self, DateTimeError> {
let new_offset = TIMEZONE_OFFSETS
.get(new_tz)
.ok_or(DateTimeError::InvalidTimezone)?
.as_ref()
.map_err(Clone::clone)?;
let datetime_with_offset =
self.datetime.assume_offset(self.offset);
let new_datetime = datetime_with_offset.to_offset(*new_offset);
Ok(Self {
datetime: PrimitiveDateTime::new(
new_datetime.date(),
new_datetime.time(),
),
offset: *new_offset,
})
}
// -------------------------------------------------------------------------
// Additional Utilities
// -------------------------------------------------------------------------
/// Gets the Unix timestamp (seconds since Unix epoch).
///
/// # Returns
///
/// Returns the number of seconds from the Unix epoch (1970-01-01T00:00:00Z).
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
///
/// let dt = DateTime::new();
/// let ts = dt.unix_timestamp();
/// ```
#[must_use]
pub const fn unix_timestamp(&self) -> i64 {
self.datetime.assume_offset(self.offset).unix_timestamp()
}
/// Calculates the duration between this `DateTime` and another.
///
/// The result can be negative if `other` is later than `self`.
///
/// # Arguments
///
/// * `other` - The `DateTime` to compare with
///
/// # Returns
///
/// Returns a `Duration` representing the time difference.
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
///
/// let dt1 = DateTime::new();
/// let dt2 = dt1.add_days(1).unwrap_or(dt1);
/// let duration = dt1.duration_since(&dt2);
/// // duration could be negative if dt2 > dt1
/// ```
#[must_use]
pub fn duration_since(&self, other: &Self) -> Duration {
let self_offset = self.datetime.assume_offset(self.offset);
let other_offset = other.datetime.assume_offset(other.offset);
let seconds_diff = self_offset.unix_timestamp()
- other_offset.unix_timestamp();
let nanos_diff = i64::from(self_offset.nanosecond())
- i64::from(other_offset.nanosecond());
Duration::seconds(seconds_diff)
+ Duration::nanoseconds(nanos_diff)
}
// -------------------------------------------------------------------------
// Date Arithmetic Methods
// -------------------------------------------------------------------------
/// Adds a specified number of days to the `DateTime`.
///
/// # Arguments
///
/// * `days` - Number of days to add (can be negative for subtraction)
///
/// # Returns
///
/// Returns a `Result` containing either the new `DateTime` or a `DateTimeError`
/// if the operation would result in an invalid date.
///
/// # Errors
///
/// This function returns a [`DateTimeError::InvalidDate`] if adding `days` results
/// in a date overflow or otherwise invalid date.
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
///
/// let dt = DateTime::new();
/// let future = dt.add_days(7);
/// assert!(future.is_ok());
/// ```
pub fn add_days(&self, days: i64) -> Result<Self, DateTimeError> {
let new_datetime = self
.datetime
.checked_add(Duration::days(days))
.ok_or(DateTimeError::InvalidDate)?;
Ok(Self {
datetime: new_datetime,
offset: self.offset,
})
}
/// Adds a specified number of months to the `DateTime`.
///
/// Handles month-end dates and leap years appropriately.
///
/// # Arguments
///
/// * `months` - Number of months to add (can be negative for subtraction)
///
/// # Returns
///
/// Returns a `Result` containing either the new `DateTime` or a `DateTimeError`
/// if the operation would result in an invalid date.
///
/// # Errors
///
/// This function returns a [`DateTimeError`] if:
/// - The calculated year, month, or day is invalid (e.g., out of range).
/// - The underlying date library fails to construct a valid date.
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
///
/// let dt = DateTime::new();
/// let future = dt.add_months(3);
/// assert!(future.is_ok());
/// ```
pub fn add_months(
&self,
months: i32,
) -> Result<Self, DateTimeError> {
let current_date = self.datetime.date();
let total_months =
current_date.year() * 12 + current_date.month() as i32 - 1
+ months;
let target_year = total_months / 12;
let target_month = u8::try_from((total_months % 12) + 1);
let target_month =
target_month.map_err(|_| DateTimeError::InvalidDate)?;
let days_in_target_month =
days_in_month(target_year, target_month)?;
let target_day = current_date.day().min(days_in_target_month);
let new_month = Month::try_from(target_month)
.map_err(|_| DateTimeError::InvalidDate)?;
let new_date = Date::from_calendar_date(
target_year,
new_month,
target_day,
)
.map_err(|_| DateTimeError::InvalidDate)?;
Ok(Self {
datetime: PrimitiveDateTime::new(
new_date,
self.datetime.time(),
),
offset: self.offset,
})
}
/// Subtracts a specified number of months from the `DateTime`.
///
/// # Arguments
///
/// * `months` - Number of months to subtract
///
/// # Returns
///
/// Returns a `Result` containing either the new `DateTime` or a `DateTimeError`
/// if the operation would result in an invalid date.
///
/// # Errors
///
/// This function returns a [`DateTimeError::InvalidDate`] if:
/// - The resulting date is out of valid range.
/// - The underlying date library fails to construct a valid `DateTime`.
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
///
/// let dt = DateTime::new();
/// let past = dt.sub_months(3);
/// assert!(past.is_ok());
/// ```
pub fn sub_months(
&self,
months: i32,
) -> Result<Self, DateTimeError> {
self.add_months(-months)
}
/// Adds a specified number of years to the `DateTime`.
///
/// Handles leap-year transitions appropriately.
///
/// # Arguments
///
/// * `years` - Number of years to add (can be negative for subtraction)
///
/// # Returns
///
/// Returns a `Result` containing either the new `DateTime` or a `DateTimeError`
/// if the operation would result in an invalid date.
///
/// # Errors
///
/// This function returns a [`DateTimeError::InvalidDate`] if:
/// - The resulting year is out of valid range.
/// - A non-leap year cannot accommodate February 29th.
/// - Any other invalid date scenario occurs during calculation.
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
///
/// let dt = DateTime::new();
/// let future = dt.add_years(5);
/// assert!(future.is_ok());
/// ```
pub fn add_years(&self, years: i32) -> Result<Self, DateTimeError> {
let current_date = self.datetime.date();
let target_year = current_date
.year()
.checked_add(years)
.ok_or(DateTimeError::InvalidDate)?;
// Handle February 29th in leap years
let new_day = if current_date.month() == Month::February
&& current_date.day() == 29
&& !is_leap_year(target_year)
{
28
} else {
current_date.day()
};
let new_date = Date::from_calendar_date(
target_year,
current_date.month(),
new_day,
)
.map_err(|_| DateTimeError::InvalidDate)?;
Ok(Self {
datetime: PrimitiveDateTime::new(
new_date,
self.datetime.time(),
),
offset: self.offset,
})
}
// -------------------------------------------------------------------------
// Range / Boundary Helper Methods
// -------------------------------------------------------------------------
/// Returns a new `DateTime` for the start of the current week (Monday).
///
/// # Errors
///
/// This function can return a [`DateTimeError`] if an overflow or
/// invalid date calculation occurs during date arithmetic.
pub fn start_of_week(&self) -> Result<Self, DateTimeError> {
let days_since_monday = i64::from(
self.datetime.weekday().number_days_from_monday(),
);
self.add_days(-days_since_monday)
}
/// Returns a new `DateTime` for the end of the current week (Sunday).
///
/// # Errors
///
/// This function can return a [`DateTimeError`] if an overflow or
/// invalid date calculation occurs during date arithmetic.
pub fn end_of_week(&self) -> Result<Self, DateTimeError> {
let days_until_sunday = 6 - i64::from(
self.datetime.weekday().number_days_from_monday(),
);
self.add_days(days_until_sunday)
}
/// Returns a new `DateTime` for the start of the current month.
///
/// # Errors
///
/// This function can return a [`DateTimeError`] if the date cannot be
/// constructed (e.g., due to an invalid year or month).
pub fn start_of_month(&self) -> Result<Self, DateTimeError> {
self.set_date(
self.datetime.year(),
self.datetime.month() as u8,
1,
)
}
/// Returns a new `DateTime` for the end of the current month.
///
/// # Errors
///
/// This function can return a [`DateTimeError`] if the date cannot be
/// constructed (e.g., `days_in_month` fails to provide a valid day).
pub fn end_of_month(&self) -> Result<Self, DateTimeError> {
let year = self.datetime.year();
let month = self.datetime.month() as u8;
let last_day = days_in_month(year, month)?;
self.set_date(year, month, last_day)
}
/// Returns a new `DateTime` for the start of the current year.
///
/// # Errors
///
/// This function can return a [`DateTimeError`] if the date cannot
/// be constructed (e.g., invalid year).
pub fn start_of_year(&self) -> Result<Self, DateTimeError> {
self.set_date(self.datetime.year(), 1, 1)
}
/// Returns a new `DateTime` for the end of the current year.
///
/// # Errors
///
/// This function can return a [`DateTimeError`] if the date cannot
/// be constructed (e.g., invalid year).
pub fn end_of_year(&self) -> Result<Self, DateTimeError> {
self.set_date(self.datetime.year(), 12, 31)
}
// -------------------------------------------------------------------------
// Range Validation
// -------------------------------------------------------------------------
/// Checks if the current `DateTime` falls within a specific date range (inclusive).
///
/// # Arguments
///
/// * `start` - Start of the date range (inclusive)
/// * `end` - End of the date range (inclusive)
///
/// # Returns
///
/// Returns `true` if the current `DateTime` falls within the range, `false` otherwise.
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
///
/// let dt = DateTime::new();
/// let start = dt.add_days(-1).unwrap_or(dt);
/// let end = dt.add_days(1).unwrap_or(dt);
///
/// assert!(dt.is_within_range(&start, &end));
/// ```
#[must_use]
pub fn is_within_range(&self, start: &Self, end: &Self) -> bool {
self >= start && self <= end
}
// -------------------------------------------------------------------------
// Mutation Helpers
// -------------------------------------------------------------------------
/// Sets the date components while maintaining the current time.
///
/// # Arguments
///
/// * `year` - Calendar year
/// * `month` - Month (1-12)
/// * `day` - Day of month (1-31)
///
/// # Returns
///
/// Returns a `Result` containing either the new `DateTime` or a `DateTimeError`
/// if the date is invalid.
///
/// # Examples
///
/// ```
/// use dtt::datetime::DateTime;
///
/// let dt = DateTime::new();
/// let new_dt = dt.set_date(2024, 1, 1);
/// assert!(new_dt.is_ok());
/// ```
///
/// # Errors
///
/// Returns a `DateTimeError` if the resulting date would be invalid.
///
pub fn set_date(
&self,
year: i32,
month: u8,
day: u8,
) -> Result<Self, DateTimeError> {
let month = Month::try_from(month)
.map_err(|_| DateTimeError::InvalidDate)?;
let new_date = Date::from_calendar_date(year, month, day)
.map_err(|_| DateTimeError::InvalidDate)?;
Ok(Self {
datetime: PrimitiveDateTime::new(
new_date,
self.datetime.time(),
),
offset: self.offset,
})
}
}
// -----------------------------------------------------------------------------
// Validation Methods
// -----------------------------------------------------------------------------
impl DateTime {
/// Validates whether a string represents a valid day of the month.
#[must_use]
pub fn is_valid_day(day: &str) -> bool {
day.parse::<u8>()
.map(|d| (1..=MAX_DAY).contains(&d))
.unwrap_or(false)
}
/// Validates whether a string represents a valid hour.
#[must_use]
pub fn is_valid_hour(hour: &str) -> bool {
hour.parse::<u8>().map(|h| h <= MAX_HOUR).unwrap_or(false)
}
/// Validates whether a string represents a valid minute.
#[must_use]
pub fn is_valid_minute(minute: &str) -> bool {
minute
.parse::<u8>()
.map(|m| m <= MAX_MIN_SEC)
.unwrap_or(false)
}
/// Validates whether a string represents a valid second.
#[must_use]
pub fn is_valid_second(second: &str) -> bool {
second
.parse::<u8>()
.map(|s| s <= MAX_MIN_SEC)
.unwrap_or(false)
}
/// Validates whether a string represents a valid month.
#[must_use]
pub fn is_valid_month(month: &str) -> bool {
month
.parse::<u8>()
.map(|m| (1..=MAX_MONTH).contains(&m))
.unwrap_or(false)
}
/// Validates whether a string represents a valid year.
#[must_use]
pub fn is_valid_year(year: &str) -> bool {
year.parse::<i32>().is_ok()
}
/// Validates whether a string represents a valid microsecond.
#[must_use]
pub fn is_valid_microsecond(microsecond: &str) -> bool {
microsecond
.parse::<u32>()
.map(|us| us <= MAX_MICROSECOND)
.unwrap_or(false)
}
/// Validates whether a string represents a valid ordinal day of the year.
#[must_use]
pub fn is_valid_ordinal(ordinal: &str) -> bool {
ordinal
.parse::<u16>()
.map(|o| (1..=MAX_ORDINAL_DAY).contains(&o))
.unwrap_or(false)
}
/// Validates whether a string represents a valid ISO week number.
#[must_use]
pub fn is_valid_iso_week(week: &str) -> bool {
week.parse::<u8>()
.map(|w| (1..=MAX_ISO_WEEK).contains(&w))
.unwrap_or(false)
}
/// Validates whether a string represents a valid time in `HH:MM:SS` format.
#[must_use]
pub fn is_valid_time(time: &str) -> bool {
let parts: Vec<&str> = time.split(':').collect();
if parts.len() != 3 {
return false;
}
Self::is_valid_hour(parts[0])
&& Self::is_valid_minute(parts[1])
&& Self::is_valid_second(parts[2])
}
}
// -----------------------------------------------------------------------------
// Standard Trait Implementations
// -----------------------------------------------------------------------------
impl fmt::Display for DateTime {
/// Formats the `DateTime` using RFC 3339 format.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.format_rfc3339()
.map_or(Err(fmt::Error), |s| write!(f, "{s}"))
}
}
impl FromStr for DateTime {
type Err = DateTimeError;
/// Parses a string into a `DateTime` instance (RFC 3339 or ISO 8601).
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::parse(s)
}
}
impl Default for DateTime {
/// Returns the current UTC time as the default `DateTime` value.
fn default() -> Self {
Self::new()
}
}
impl Add<Duration> for DateTime {
type Output = Result<Self, DateTimeError>;
/// Adds a Duration to the `DateTime`.
///
/// # Arguments
///
/// * `rhs` - Duration to add
///
/// # Returns
///
/// Returns a `Result` containing either the new `DateTime` or a `DateTimeError`.
fn add(self, rhs: Duration) -> Self::Output {
let maybe_new = self.datetime.checked_add(rhs);
maybe_new.map_or(
Err(DateTimeError::InvalidDate),
|new_datetime| {
Ok(Self {
datetime: new_datetime,
offset: self.offset,
})
},
)
}
}
impl Sub<Duration> for DateTime {
type Output = Result<Self, DateTimeError>;
/// Subtracts a Duration from the `DateTime`.
///
/// # Arguments
///
/// * `rhs` - Duration to subtract
///
/// # Returns
///
/// Returns a `Result` containing either the new `DateTime` or a `DateTimeError`.
fn sub(self, rhs: Duration) -> Self::Output {
let maybe_new = self.datetime.checked_sub(rhs);
maybe_new.map_or(
Err(DateTimeError::InvalidDate),
|new_datetime| {
Ok(Self {
datetime: new_datetime,
offset: self.offset,
})
},
)
}
}
impl PartialOrd for DateTime {
/// Compares two `DateTime` for ordering, returning `Some(Ordering)`.
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for DateTime {
/// Compares two `DateTimes` for ordering.
fn cmp(&self, other: &Self) -> Ordering {
self.datetime.cmp(&other.datetime)
}
}
impl Hash for DateTime {
/// Computes a hash value for the `DateTime` based on its components.
fn hash<H: Hasher>(&self, state: &mut H) {
self.datetime.hash(state);
self.offset.hash(state);
}
}
// -----------------------------------------------------------------------------
// Helper Functions
// -----------------------------------------------------------------------------
/// Helper function to determine the number of days in a given month and year.
///
/// # Arguments
///
/// * `year` - Calendar year
/// * `month` - Month number (1-12)
///
/// # Returns
///
/// Returns a `Result` containing either the number of days or a `DateTimeError`.
///
/// # Errors
///
/// Returns a `DateTimeError` if the day in the month is invalid.
///
pub const fn days_in_month(
year: i32,
month: u8,
) -> Result<u8, DateTimeError> {
match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => Ok(31),
4 | 6 | 9 | 11 => Ok(30),
2 => Ok(if is_leap_year(year) { 29 } else { 28 }),
_ => Err(DateTimeError::InvalidDate),
}
}
/// Helper function to determine if a year is a leap year.
///
/// # Arguments
///
/// * `year` - Calendar year to check
///
/// # Returns
///
/// Returns `true` if the year is a leap year, `false` otherwise.
///
/// # Examples
///
/// ```
/// use dtt::datetime::is_leap_year;
///
/// assert!(is_leap_year(2024));
/// assert!(!is_leap_year(2023));
/// assert!(is_leap_year(2000));
/// assert!(!is_leap_year(1900));
/// ```
#[must_use]
pub const fn is_leap_year(year: i32) -> bool {
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
}
// -----------------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use std::str::FromStr;
#[test]
fn test_new() {
let dt = DateTime::new();
assert_eq!(dt.offset(), UtcOffset::UTC);
}
#[test]
fn test_new_with_tz() {
let est = DateTime::new_with_tz("EST");
assert!(est.is_ok());
if let Ok(est_dt) = est {
assert_eq!(est_dt.offset().whole_hours(), -5);
}
let invalid = DateTime::new_with_tz("INVALID");
assert!(matches!(invalid, Err(DateTimeError::InvalidTimezone)));
}
#[test]
fn test_new_with_custom_offset() {
let offset = DateTime::new_with_custom_offset(5, 30);
assert!(offset.is_ok());
if let Ok(dt) = offset {
assert_eq!(dt.offset().whole_hours(), 5);
assert_eq!(dt.offset().minutes_past_hour(), 30);
}
// Test invalid offsets
let too_large_hours = DateTime::new_with_custom_offset(24, 0);
assert!(too_large_hours.is_err());
let too_large_minutes = DateTime::new_with_custom_offset(0, 60);
assert!(too_large_minutes.is_err());
}
#[test]
fn test_from_components() {
let dt = DateTime::from_components(
2024,
1,
1,
12,
0,
0,
UtcOffset::UTC,
);
assert!(dt.is_ok());
if let Ok(dt_val) = dt {
assert_eq!(dt_val.year(), 2024);
assert_eq!(dt_val.month(), Month::January);
assert_eq!(dt_val.day(), 1);
assert_eq!(dt_val.hour(), 12);
assert_eq!(dt_val.minute(), 0);
assert_eq!(dt_val.second(), 0);
}
// Test invalid dates
let invalid_month = DateTime::from_components(
2024,
13,
1,
0,
0,
0,
UtcOffset::UTC,
);
assert!(invalid_month.is_err());
let invalid_day = DateTime::from_components(
2024,
2,
30,
0,
0,
0,
UtcOffset::UTC,
);
assert!(invalid_day.is_err());
}
#[test]
fn test_parse() {
// Test RFC 3339 format
let dt = DateTime::parse("2024-01-01T12:00:00Z");
assert!(dt.is_ok());
// Test ISO 8601 date
let dt = DateTime::parse("2024-01-01");
assert!(dt.is_ok());
if let Ok(dt_val) = dt {
assert_eq!(dt_val.hour(), 0);
assert_eq!(dt_val.minute(), 0);
}
// Test invalid formats
let invalid1 = DateTime::parse("invalid");
assert!(invalid1.is_err());
let invalid2 = DateTime::parse("2024-13-01");
assert!(invalid2.is_err());
}
#[test]
fn test_format() {
let dt = DateTime::new();
let maybe_formatted = dt.format("[year]-[month]-[day]");
assert!(maybe_formatted.is_ok());
let invalid_format = dt.format("[invalid]");
assert!(invalid_format.is_err());
}
#[test]
fn test_timezone_conversion() {
let utc = DateTime::new();
let est = utc.convert_to_tz("EST");
assert!(est.is_ok());
if let Ok(est_val) = est {
assert_eq!(est_val.offset().whole_hours(), -5);
}
let invalid = utc.convert_to_tz("INVALID");
assert!(invalid.is_err());
}
#[test]
fn test_arithmetic() {
let dt = DateTime::new();
// Test adding days
let future = dt.add_days(7);
assert!(future.is_ok());
// Test subtracting days (negative)
let past = dt.add_days(-7);
assert!(past.is_ok());
// Test adding months
let next_month = dt.add_months(1);
assert!(next_month.is_ok());
// Test month edge cases
let jan31 = DateTime::from_components(
2024,
1,
31,
0,
0,
0,
UtcOffset::UTC,
);
assert!(jan31.is_ok());
if let Ok(jan31_dt) = jan31 {
let feb = jan31_dt.add_months(1);
assert!(feb.is_ok());
if let Ok(feb_dt) = feb {
// 2024 is a leap year => Feb has 29 days
assert_eq!(feb_dt.day(), 29);
}
}
}
#[test]
fn test_leap_year() {
assert!(is_leap_year(2024));
assert!(!is_leap_year(2023));
assert!(is_leap_year(2000));
assert!(!is_leap_year(1900));
}
#[test]
fn test_validation() {
// Test day validation
assert!(DateTime::is_valid_day("1"));
assert!(DateTime::is_valid_day("31"));
assert!(!DateTime::is_valid_day("0"));
assert!(!DateTime::is_valid_day("32"));
assert!(!DateTime::is_valid_day("abc"));
// Test hour validation
assert!(DateTime::is_valid_hour("0"));
assert!(DateTime::is_valid_hour("23"));
assert!(!DateTime::is_valid_hour("24"));
// Test minute validation
assert!(DateTime::is_valid_minute("0"));
assert!(DateTime::is_valid_minute("59"));
assert!(!DateTime::is_valid_minute("60"));
// Test time string validation
assert!(DateTime::is_valid_time("00:00:00"));
assert!(DateTime::is_valid_time("23:59:59"));
assert!(!DateTime::is_valid_time("24:00:00"));
assert!(!DateTime::is_valid_time("23:60:00"));
assert!(!DateTime::is_valid_time("23:59:60"));
}
#[test]
fn test_range_operations() {
let dt = DateTime::from_components(
2024,
1,
15,
12,
0,
0,
UtcOffset::UTC,
);
assert!(dt.is_ok());
if let Ok(dt_val) = dt {
// Test week ranges
let week_start = dt_val.start_of_week();
assert!(week_start.is_ok());
if let Ok(ws) = week_start {
assert_eq!(ws.weekday(), Weekday::Monday);
}
let week_end = dt_val.end_of_week();
assert!(week_end.is_ok());
if let Ok(we) = week_end {
assert_eq!(we.weekday(), Weekday::Sunday);
}
// Test month ranges
let month_start = dt_val.start_of_month();
assert!(month_start.is_ok());
if let Ok(ms) = month_start {
assert_eq!(ms.day(), 1);
}
let month_end = dt_val.end_of_month();
assert!(month_end.is_ok());
if let Ok(me) = month_end {
assert_eq!(me.day(), 31);
}
// Test year ranges
let year_start = dt_val.start_of_year();
assert!(year_start.is_ok());
if let Ok(ys) = year_start {
assert_eq!(ys.month(), Month::January);
assert_eq!(ys.day(), 1);
}
let year_end = dt_val.end_of_year();
assert!(year_end.is_ok());
if let Ok(ye) = year_end {
assert_eq!(ye.month(), Month::December);
assert_eq!(ye.day(), 31);
}
}
}
#[test]
fn test_ordering() {
let dt1 = DateTime::from_components(
2024,
1,
1,
0,
0,
0,
UtcOffset::UTC,
);
let dt2 = DateTime::from_components(
2024,
1,
2,
0,
0,
0,
UtcOffset::UTC,
);
assert!(dt1.is_ok());
assert!(dt2.is_ok());
if let (Ok(a), Ok(b)) = (dt1, dt2) {
assert!(a < b);
assert!(b > a);
assert_ne!(a, b);
}
}
#[test]
fn test_duration() {
let dt1 = DateTime::from_components(
2024,
1,
1,
0,
0,
0,
UtcOffset::UTC,
);
let dt2 = DateTime::from_components(
2024,
1,
2,
0,
0,
0,
UtcOffset::UTC,
);
if let (Ok(a), Ok(b)) = (dt1, dt2) {
let duration = b.duration_since(&a);
assert_eq!(duration.whole_days(), 1);
}
}
#[test]
fn test_from_str() {
let dt = DateTime::from_str("2024-01-01T00:00:00Z");
assert!(dt.is_ok());
let invalid = DateTime::from_str("invalid");
assert!(invalid.is_err());
}
#[test]
fn test_display() {
let dt = DateTime::from_components(
2024,
1,
1,
0,
0,
0,
UtcOffset::UTC,
);
assert!(dt.is_ok());
if let Ok(dt_val) = dt {
assert_eq!(dt_val.to_string(), "2024-01-01T00:00:00Z");
}
}
#[test]
fn test_hash() {
use std::collections::HashSet;
let dt1 = DateTime::from_components(
2024,
1,
1,
0,
0,
0,
UtcOffset::UTC,
);
let dt2 = DateTime::from_components(
2024,
1,
1,
0,
0,
0,
UtcOffset::UTC,
);
assert!(dt1.is_ok());
assert!(dt2.is_ok());
if let (Ok(a), Ok(b)) = (dt1, dt2) {
let mut set = HashSet::new();
assert!(
set.insert(a),
"The set should not have contained `a` before"
);
assert!(set.contains(&b));
}
}
#[test]
fn test_builder_pattern() {
let builder = DateTimeBuilder::new()
.year(2024)
.month(1)
.day(1)
.hour(12)
.minute(30)
.second(45)
.offset(UtcOffset::UTC);
let dt = builder.build();
assert!(dt.is_ok());
if let Ok(value) = dt {
assert_eq!(value.year(), 2024);
assert_eq!(value.month(), Month::January);
assert_eq!(value.day(), 1);
assert_eq!(value.hour(), 12);
assert_eq!(value.minute(), 30);
assert_eq!(value.second(), 45);
}
}
}