Skip to content

Commit

Permalink
Change DateOfBirth data
Browse files Browse the repository at this point in the history
  • Loading branch information
bouzuya committed Dec 5, 2023
1 parent 4230550 commit 454ddfa
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 7 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion Cargo.toml
Expand Up @@ -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"] }
Expand Down
28 changes: 22 additions & 6 deletions 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 {
Expand All @@ -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)
}
}

Expand All @@ -35,8 +41,18 @@ impl FromStr for DateOfBirth {
fn from_str(s: &str) -> Result<Self, Self::Err> {
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<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(
&self
.0
.format(&format_description!("[year]-[month]-[day]"))
.expect("invalid format"),
)
}
}

Expand Down

0 comments on commit 454ddfa

Please sign in to comment.