From 454ddfa9db567f8c85c0d20e3d32145b955ce0fc Mon Sep 17 00:00:00 2001 From: bouzuya Date: Wed, 6 Dec 2023 07:09:07 +0900 Subject: [PATCH] Change DateOfBirth data --- Cargo.lock | 1 + Cargo.toml | 7 ++++++- src/model/date_of_birth.rs | 28 ++++++++++++++++++++++------ 3 files changed, 29 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cc72a33..789d0c1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -312,6 +312,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8eb30d70a07a3b04884d2677f06bec33509dc67ca60d92949e5535352d3191dc" dependencies = [ "powerfmt", + "serde", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 7683053..e9b36a0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,7 +17,12 @@ scraper = "0.18.1" serde = { version = "1.0.171", features = ["derive"] } serde_json = "1.0.103" thiserror = "1.0.44" -time = { version = "0.3.23", features = ["formatting", "parsing", "macros"] } +time = { version = "0.3.23", features = [ + "formatting", + "macros", + "parsing", + "serde", +] } tokio = { version = "1.29.1", features = ["full"] } tower = "0.4.13" tower-http = { version = "0.5.0", features = ["trace", "request-id"] } diff --git a/src/model/date_of_birth.rs b/src/model/date_of_birth.rs index 0039311..ed96a63 100644 --- a/src/model/date_of_birth.rs +++ b/src/model/date_of_birth.rs @@ -1,10 +1,10 @@ use std::str::FromStr; use rand::{thread_rng, Rng}; -use time::{macros::format_description, Date, OffsetDateTime}; +use time::{macros::format_description, Date, Month, OffsetDateTime}; -#[derive(Debug, Eq, PartialEq, serde::Serialize)] -pub struct DateOfBirth(String); +#[derive(Debug, Eq, PartialEq)] +pub struct DateOfBirth(Date); impl DateOfBirth { pub fn gen() -> Self { @@ -25,7 +25,13 @@ impl DateOfBirth { _ => 31, }; let day = rng.gen_range(1..=last_day_of_month); - Self(format!("{:04}-{:02}-{:02}", year, month, day)) + let date = Date::from_calendar_date( + year, + Month::try_from(month as u8).expect("invalid month"), + day, + ) + .expect("invalid date"); + Self(date) } } @@ -35,8 +41,18 @@ impl FromStr for DateOfBirth { fn from_str(s: &str) -> Result { let format = format_description!("[year]-[month]-[day]"); let date = Date::parse(s, &format)?; - let s = date.format(&format)?; - Ok(Self(s)) + Ok(Self(date)) + } +} + +impl serde::Serialize for DateOfBirth { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str( + &self + .0 + .format(&format_description!("[year]-[month]-[day]")) + .expect("invalid format"), + ) } }