chrono/naive/isoweek.rs
1// This is a part of Chrono.
2// See README.md and LICENSE.txt for details.
3
4//! ISO 8601 week.
5
6use core::fmt;
7
8use super::internals::{DateImpl, Of, YearFlags};
9
10#[cfg(feature = "rkyv")]
11use rkyv::{Archive, Deserialize, Serialize};
12
13/// ISO 8601 week.
14///
15/// This type, combined with [`Weekday`](../enum.Weekday.html),
16/// constitutes the ISO 8601 [week date](./struct.NaiveDate.html#week-date).
17/// One can retrieve this type from the existing [`Datelike`](../trait.Datelike.html) types
18/// via the [`Datelike::iso_week`](../trait.Datelike.html#tymethod.iso_week) method.
19#[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone, Hash)]
20#[cfg_attr(feature = "rkyv", derive(Archive, Deserialize, Serialize))]
21pub struct IsoWeek {
22 // note that this allows for larger year range than `NaiveDate`.
23 // this is crucial because we have an edge case for the first and last week supported,
24 // which year number might not match the calendar year number.
25 ywf: DateImpl, // (year << 10) | (week << 4) | flag
26}
27
28/// Returns the corresponding `IsoWeek` from the year and the `Of` internal value.
29//
30// internal use only. we don't expose the public constructor for `IsoWeek` for now,
31// because the year range for the week date and the calendar date do not match and
32// it is confusing to have a date that is out of range in one and not in another.
33// currently we sidestep this issue by making `IsoWeek` fully dependent of `Datelike`.
34pub(super) fn iso_week_from_yof(year: i32, of: Of) -> IsoWeek {
35 let (rawweek, _) = of.isoweekdate_raw();
36 let (year, week) = if rawweek < 1 {
37 // previous year
38 let prevlastweek = YearFlags::from_year(year - 1).nisoweeks();
39 (year - 1, prevlastweek)
40 } else {
41 let lastweek = of.flags().nisoweeks();
42 if rawweek > lastweek {
43 // next year
44 (year + 1, 1)
45 } else {
46 (year, rawweek)
47 }
48 };
49 let flags = YearFlags::from_year(year);
50 IsoWeek { ywf: (year << 10) | (week << 4) as DateImpl | DateImpl::from(flags.0) }
51}
52
53impl IsoWeek {
54 /// Returns the year number for this ISO week.
55 ///
56 /// # Example
57 ///
58 /// ```
59 /// use chrono::{NaiveDate, Datelike, Weekday};
60 ///
61 /// let d = NaiveDate::from_isoywd_opt(2015, 1, Weekday::Mon).unwrap();
62 /// assert_eq!(d.iso_week().year(), 2015);
63 /// ```
64 ///
65 /// This year number might not match the calendar year number.
66 /// Continuing the example...
67 ///
68 /// ```
69 /// # use chrono::{NaiveDate, Datelike, Weekday};
70 /// # let d = NaiveDate::from_isoywd_opt(2015, 1, Weekday::Mon).unwrap();
71 /// assert_eq!(d.year(), 2014);
72 /// assert_eq!(d, NaiveDate::from_ymd_opt(2014, 12, 29).unwrap());
73 /// ```
74 #[inline]
75 pub const fn year(&self) -> i32 {
76 self.ywf >> 10
77 }
78
79 /// Returns the ISO week number starting from 1.
80 ///
81 /// The return value ranges from 1 to 53. (The last week of year differs by years.)
82 ///
83 /// # Example
84 ///
85 /// ```
86 /// use chrono::{NaiveDate, Datelike, Weekday};
87 ///
88 /// let d = NaiveDate::from_isoywd_opt(2015, 15, Weekday::Mon).unwrap();
89 /// assert_eq!(d.iso_week().week(), 15);
90 /// ```
91 #[inline]
92 pub const fn week(&self) -> u32 {
93 ((self.ywf >> 4) & 0x3f) as u32
94 }
95
96 /// Returns the ISO week number starting from 0.
97 ///
98 /// The return value ranges from 0 to 52. (The last week of year differs by years.)
99 ///
100 /// # Example
101 ///
102 /// ```
103 /// use chrono::{NaiveDate, Datelike, Weekday};
104 ///
105 /// let d = NaiveDate::from_isoywd_opt(2015, 15, Weekday::Mon).unwrap();
106 /// assert_eq!(d.iso_week().week0(), 14);
107 /// ```
108 #[inline]
109 pub const fn week0(&self) -> u32 {
110 ((self.ywf >> 4) & 0x3f) as u32 - 1
111 }
112}
113
114/// The `Debug` output of the ISO week `w` is the same as
115/// [`d.format("%G-W%V")`](../format/strftime/index.html)
116/// where `d` is any `NaiveDate` value in that week.
117///
118/// # Example
119///
120/// ```
121/// use chrono::{NaiveDate, Datelike};
122///
123/// assert_eq!(format!("{:?}", NaiveDate::from_ymd_opt(2015, 9, 5).unwrap().iso_week()), "2015-W36");
124/// assert_eq!(format!("{:?}", NaiveDate::from_ymd_opt( 0, 1, 3).unwrap().iso_week()), "0000-W01");
125/// assert_eq!(format!("{:?}", NaiveDate::from_ymd_opt(9999, 12, 31).unwrap().iso_week()), "9999-W52");
126/// ```
127///
128/// ISO 8601 requires an explicit sign for years before 1 BCE or after 9999 CE.
129///
130/// ```
131/// # use chrono::{NaiveDate, Datelike};
132/// assert_eq!(format!("{:?}", NaiveDate::from_ymd_opt( 0, 1, 2).unwrap().iso_week()), "-0001-W52");
133/// assert_eq!(format!("{:?}", NaiveDate::from_ymd_opt(10000, 12, 31).unwrap().iso_week()), "+10000-W52");
134/// ```
135impl fmt::Debug for IsoWeek {
136 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
137 let year = self.year();
138 let week = self.week();
139 if (0..=9999).contains(&year) {
140 write!(f, "{:04}-W{:02}", year, week)
141 } else {
142 // ISO 8601 requires the explicit sign for out-of-range years
143 write!(f, "{:+05}-W{:02}", year, week)
144 }
145 }
146}
147
148#[cfg(test)]
149mod tests {
150 use crate::naive::{internals, NaiveDate};
151 use crate::Datelike;
152
153 #[test]
154 fn test_iso_week_extremes() {
155 let minweek = NaiveDate::MIN.iso_week();
156 let maxweek = NaiveDate::MAX.iso_week();
157
158 assert_eq!(minweek.year(), internals::MIN_YEAR);
159 assert_eq!(minweek.week(), 1);
160 assert_eq!(minweek.week0(), 0);
161 #[cfg(any(feature = "alloc", feature = "std"))]
162 assert_eq!(format!("{:?}", minweek), NaiveDate::MIN.format("%G-W%V").to_string());
163
164 assert_eq!(maxweek.year(), internals::MAX_YEAR + 1);
165 assert_eq!(maxweek.week(), 1);
166 assert_eq!(maxweek.week0(), 0);
167 #[cfg(any(feature = "alloc", feature = "std"))]
168 assert_eq!(format!("{:?}", maxweek), NaiveDate::MAX.format("%G-W%V").to_string());
169 }
170
171 #[test]
172 fn test_iso_week_equivalence_for_first_week() {
173 let monday = NaiveDate::from_ymd_opt(2024, 12, 30).unwrap();
174 let friday = NaiveDate::from_ymd_opt(2025, 1, 3).unwrap();
175
176 assert_eq!(monday.iso_week(), friday.iso_week());
177 }
178
179 #[test]
180 fn test_iso_week_equivalence_for_last_week() {
181 let monday = NaiveDate::from_ymd_opt(2026, 12, 28).unwrap();
182 let friday = NaiveDate::from_ymd_opt(2027, 1, 1).unwrap();
183
184 assert_eq!(monday.iso_week(), friday.iso_week());
185 }
186
187 #[test]
188 fn test_iso_week_ordering_for_first_week() {
189 let monday = NaiveDate::from_ymd_opt(2024, 12, 30).unwrap();
190 let friday = NaiveDate::from_ymd_opt(2025, 1, 3).unwrap();
191
192 assert!(monday.iso_week() >= friday.iso_week());
193 assert!(monday.iso_week() <= friday.iso_week());
194 }
195
196 #[test]
197 fn test_iso_week_ordering_for_last_week() {
198 let monday = NaiveDate::from_ymd_opt(2026, 12, 28).unwrap();
199 let friday = NaiveDate::from_ymd_opt(2027, 1, 1).unwrap();
200
201 assert!(monday.iso_week() >= friday.iso_week());
202 assert!(monday.iso_week() <= friday.iso_week());
203 }
204}