Skip to content

Commit

Permalink
date-time: add LocalDate::from_ymd
Browse files Browse the repository at this point in the history
  • Loading branch information
bouzuya committed Oct 11, 2021
1 parent f8d418b commit d186252
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions date_time/src/local_date.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,27 @@ pub enum ParseDateError {
ParseYear(ParseYearError),
}

#[derive(Debug, Eq, Error, PartialEq)]
#[error("invalid local date error")]
pub struct InvalidLocalDateError;

impl LocalDate {
pub fn from_ymd(
year: Year,
month: Month,
day_of_month: DayOfMonth,
) -> Result<Self, InvalidLocalDateError> {
let year_month = YearMonth::new(year, month);
if day_of_month > year_month.last_day_of_month() {
return Err(InvalidLocalDateError);
}
Ok(Self {
year,
month,
day_of_month,
})
}

pub fn day_of_month(&self) -> DayOfMonth {
self.day_of_month
}
Expand Down Expand Up @@ -96,6 +116,27 @@ mod tests {

use super::*;

#[test]
fn from_ymd_test() -> anyhow::Result<()> {
assert_eq!(
LocalDate::from_ymd(
Year::from_str("2021")?,
Month::from_str("02")?,
DayOfMonth::from_str("03")?
)?,
LocalDate::from_str("2021-02-03")?
);
assert!(matches!(
LocalDate::from_ymd(
Year::from_str("2021")?,
Month::from_str("02")?,
DayOfMonth::from_str("31")?
),
Err(InvalidLocalDateError)
));
Ok(())
}

#[test]
fn str_conversion_test() {
type E = ParseDateError;
Expand Down

0 comments on commit d186252

Please sign in to comment.