1use chrono::{Datelike, NaiveDate, Utc};
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5#[non_exhaustive]
6pub enum DateFormat {
7 YmdHyphen,
9 DmyHyphen,
11 YmdDot,
13 DmyDot,
15}
16
17impl DateFormat {
18 #[must_use]
20 pub const fn pattern(self) -> &'static str {
21 match self {
22 Self::YmdHyphen => "%Y-%m-%d",
23 Self::DmyHyphen => "%d-%m-%Y",
24 Self::YmdDot => "%Y.%m.%d",
25 Self::DmyDot => "%d.%m.%Y",
26 }
27 }
28
29 #[must_use]
31 pub const fn reversed(self) -> Self {
32 match self {
33 Self::YmdHyphen => Self::DmyHyphen,
34 Self::DmyHyphen => Self::YmdHyphen,
35 Self::YmdDot => Self::DmyDot,
36 Self::DmyDot => Self::YmdDot,
37 }
38 }
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
50pub struct BirthDate(NaiveDate);
51
52impl BirthDate {
53 pub const DEFAULT_FORMAT: DateFormat = DateFormat::YmdHyphen;
55 pub const MIN_YEAR: i32 = 1800;
63
64 pub fn parse(value: &str) -> Result<Self, BirthDateError> {
66 Self::parse_with_format(value, Self::DEFAULT_FORMAT)
67 }
68
69 pub fn parse_with_format(value: &str, format: DateFormat) -> Result<Self, BirthDateError> {
71 Self::parse_with_format_at(value, format, Self::today_utc())
72 }
73
74 pub fn parse_with_format_at(
76 value: &str,
77 format: DateFormat,
78 today: NaiveDate,
79 ) -> Result<Self, BirthDateError> {
80 let date = NaiveDate::parse_from_str(value.trim(), format.pattern())
81 .map_err(|_| BirthDateError::Date)?;
82 Self::from_naive_date_at(date, today)
83 }
84
85 pub fn from_naive_date(date: NaiveDate) -> Result<Self, BirthDateError> {
87 Self::from_naive_date_at(date, Self::today_utc())
88 }
89
90 pub fn from_naive_date_at(date: NaiveDate, today: NaiveDate) -> Result<Self, BirthDateError> {
92 if date.year() < Self::MIN_YEAR {
93 return Err(BirthDateError::TooOld);
94 }
95 if date > today.succ_opt().unwrap_or(today) {
96 return Err(BirthDateError::FutureDate);
97 }
98 Ok(Self(date))
99 }
100
101 fn today_utc() -> NaiveDate {
103 Utc::now().date_naive()
104 }
105
106 #[inline]
108 #[must_use]
109 pub fn as_naive_date(&self) -> NaiveDate {
110 self.0
111 }
112
113 #[must_use]
115 pub fn format_as(&self, format: DateFormat) -> String {
116 self.0.format(format.pattern()).to_string()
117 }
118
119 #[must_use]
121 pub fn year(&self) -> i32 {
122 self.0.year()
123 }
124 #[must_use]
126 pub fn month(&self) -> u32 {
127 self.0.month()
128 }
129 #[must_use]
131 pub fn day(&self) -> u32 {
132 self.0.day()
133 }
134
135 #[must_use]
137 pub fn age(&self) -> u32 {
138 self.age_at(Self::today_utc())
139 }
140
141 #[must_use]
143 pub fn age_at(&self, date: NaiveDate) -> u32 {
144 if date <= self.0 {
145 return 0;
146 }
147 let mut years = date.year() - self.0.year();
148 if (date.month(), date.day()) < (self.0.month(), self.0.day()) {
149 years -= 1;
150 }
151 u32::try_from(years).unwrap_or(0)
152 }
153}
154
155impl core::fmt::Display for BirthDate {
156 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
157 write!(f, "{}", self.0.format(Self::DEFAULT_FORMAT.pattern()))
158 }
159}
160
161impl core::str::FromStr for BirthDate {
162 type Err = BirthDateError;
163 fn from_str(s: &str) -> Result<Self, BirthDateError> {
164 Self::parse(s)
165 }
166}
167
168impl TryFrom<&str> for BirthDate {
169 type Error = BirthDateError;
170 fn try_from(value: &str) -> Result<Self, BirthDateError> {
171 Self::parse(value)
172 }
173}
174
175impl TryFrom<String> for BirthDate {
176 type Error = BirthDateError;
177 fn try_from(value: String) -> Result<Self, BirthDateError> {
178 Self::parse(&value)
179 }
180}
181
182impl TryFrom<NaiveDate> for BirthDate {
183 type Error = BirthDateError;
184 fn try_from(value: NaiveDate) -> Result<Self, BirthDateError> {
185 Self::from_naive_date(value)
186 }
187}
188
189impl From<BirthDate> for NaiveDate {
190 fn from(value: BirthDate) -> Self {
191 value.0
192 }
193}
194
195impl AsRef<NaiveDate> for BirthDate {
196 fn as_ref(&self) -> &NaiveDate {
197 &self.0
198 }
199}
200
201#[cfg(feature = "serde")]
202impl serde::Serialize for BirthDate {
203 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
204 serializer.collect_str(self)
205 }
206}
207
208#[cfg(feature = "serde")]
209impl<'de> serde::Deserialize<'de> for BirthDate {
210 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
211 crate::serde_support::deserialize_string_newtype(
212 deserializer,
213 "a birth date in YYYY-MM-DD format",
214 )
215 }
216}
217
218#[cfg(any(feature = "sqlx-0_8", feature = "sqlx-0_9"))]
219crate::sqlx_support::sqlx_via!(
220 BirthDate,
221 NaiveDate,
222 |d: NaiveDate| BirthDate::from_naive_date(d),
223 |this: &BirthDate| &this.0
224);
225
226#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
228#[non_exhaustive]
229pub enum BirthDateError {
230 #[error("invalid birth date format or value")]
232 Date,
233 #[error("birth date cannot be in the future")]
235 FutureDate,
236 #[error(
238 "birth date is too far in the past, year must be >= {}",
239 BirthDate::MIN_YEAR
240 )]
241 TooOld,
242}
243
244#[cfg(test)]
245mod tests {
246 use super::*;
247
248 #[test]
249 fn deterministic_boundaries() {
250 let today = NaiveDate::from_ymd_opt(2026, 9, 3).unwrap();
251 assert!(BirthDate::from_naive_date_at(today.succ_opt().unwrap(), today).is_ok());
252 assert_eq!(
253 BirthDate::parse_with_format_at("2026-09-05", DateFormat::YmdHyphen, today),
254 Err(BirthDateError::FutureDate)
255 );
256 assert!(BirthDate::parse("1800-01-01").is_ok());
258 assert_eq!(BirthDate::parse("1799-12-31"), Err(BirthDateError::TooOld));
259 assert_eq!(BirthDate::parse("15.05.1990"), Err(BirthDateError::Date));
260 assert_eq!(BirthDate::parse("1990-05-15").unwrap().age_at(today), 36);
261 }
262}