dos_date_time/dos_date/
fmt.rs

1// SPDX-FileCopyrightText: 2025 Shun Sakai
2//
3// SPDX-License-Identifier: Apache-2.0 OR MIT
4
5//! Utilities for formatting and printing [`Date`].
6
7use core::fmt;
8
9use super::Date;
10
11impl fmt::Display for Date {
12    /// Shows the value of this `Date` in the well-known [RFC 3339 format].
13    ///
14    /// # Examples
15    ///
16    /// ```
17    /// # use dos_date_time::Date;
18    /// #
19    /// assert_eq!(format!("{}", Date::MIN), "1980-01-01");
20    /// assert_eq!(format!("{}", Date::MAX), "2107-12-31");
21    /// ```
22    ///
23    /// [RFC 3339 format]: https://datatracker.ietf.org/doc/html/rfc3339#section-5.6
24    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25        let (year, month, day) = (self.year(), u8::from(self.month()), self.day());
26        write!(f, "{year:04}-{month:02}-{day:02}")
27    }
28}
29
30#[cfg(test)]
31mod tests {
32    use time::macros::date;
33
34    use super::*;
35
36    #[test]
37    fn debug() {
38        assert_eq!(format!("{:?}", Date::MIN), "Date(33)");
39        // <https://devblogs.microsoft.com/oldnewthing/20030905-02/?p=42653>.
40        assert_eq!(
41            format!("{:?}", Date::from_date(date!(2002-11-26)).unwrap()),
42            "Date(11642)"
43        );
44        // <https://github.com/zip-rs/zip/blob/v0.6.4/src/types.rs#L553-L569>.
45        assert_eq!(
46            format!("{:?}", Date::from_date(date!(2018-11-17)).unwrap()),
47            "Date(19825)"
48        );
49        assert_eq!(format!("{:?}", Date::MAX), "Date(65439)");
50    }
51
52    #[test]
53    fn display() {
54        assert_eq!(format!("{}", Date::MIN), "1980-01-01");
55        // <https://devblogs.microsoft.com/oldnewthing/20030905-02/?p=42653>.
56        assert_eq!(
57            format!("{}", Date::from_date(date!(2002-11-26)).unwrap()),
58            "2002-11-26"
59        );
60        // <https://github.com/zip-rs/zip/blob/v0.6.4/src/types.rs#L553-L569>.
61        assert_eq!(
62            format!("{}", Date::from_date(date!(2018-11-17)).unwrap()),
63            "2018-11-17"
64        );
65        assert_eq!(format!("{}", Date::MAX), "2107-12-31");
66    }
67}