Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created June 3, 2020 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rust-play/c31df2abc1ba74a7ba272e7bc1a71e80 to your computer and use it in GitHub Desktop.
Save rust-play/c31df2abc1ba74a7ba272e7bc1a71e80 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use std::convert::TryInto;
use chrono::prelude::*; // 0.4.11
pub struct Mondays {}
impl Mondays {
pub fn count(birth: chrono::NaiveDate, curr_date: chrono::NaiveDate) -> i64 {
// start work at age 22
let start_work = birth + chrono::Duration::days(22 * 365);
// retire at age 78
let retire = birth + chrono::Duration::days(78 * 365);
// check if they have retired or not
let end_work = if curr_date > retire { retire } else { curr_date };
// check days from monday, if 0 set to 7
let start_from_monday = match start_work.weekday().num_days_from_monday() {
0 => 7,
x => x,
};
// get first monday
let first_monday = start_work + chrono::Duration::days((7 - start_from_monday).try_into().unwrap());
// get last monday
let last_monday = end_work - chrono::Duration::days((end_work.weekday().num_days_from_monday()).try_into().unwrap());
// count days between mondays
let between_mondays = last_monday.signed_duration_since(first_monday).num_days();
// if more than 7 days, div by 7
if between_mondays > 7 {
between_mondays / 7
} else if between_mondays >= 0 {
1
} else {
0
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1() {
assert_eq!(Mondays::count(chrono::NaiveDate::from_ymd(1995, 4, 3), chrono::NaiveDate::from_ymd(2017, 4, 3)), 1);
}
#[test]
fn test_2() {
assert_eq!(Mondays::count(chrono::NaiveDate::from_ymd(1995, 4, 2), chrono::NaiveDate::from_ymd(2018, 4, 2)), 53);
}
#[test]
fn test_3() {
assert_eq!(Mondays::count(chrono::NaiveDate::from_ymd(1995, 4, 2), chrono::NaiveDate::from_ymd(2017, 3, 2)), 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment