Skip to content

Instantly share code, notes, and snippets.

@virtualritz
Last active April 19, 2022 12:12
Show Gist options
  • Save virtualritz/585c80b0eb866d1047b719b2d2365463 to your computer and use it in GitHub Desktop.
Save virtualritz/585c80b0eb866d1047b719b2d2365463 to your computer and use it in GitHub Desktop.
Find the next Friday from today in Rust
use chrono::{offset::Utc, Datelike, Duration}; // 0.4.19
fn main() {
let today_naive = Utc::today()
.naive_utc()
.checked_add_signed(Duration::days(0))
.unwrap();
let num_days_from_monday = today_naive.weekday().num_days_from_monday();
// Using an if ... block here avoids any signed arithmetic.
let next_friday = if num_days_from_monday < 4 {
today_naive
.checked_add_signed(Duration::days((4 - num_days_from_monday) as _))
.unwrap()
} else {
today_naive
.checked_add_signed(Duration::days((11 - num_days_from_monday) as _))
.unwrap()
};
println!("Today is {}, next Friday is {}", today_naive, next_friday,);
}
@virtualritz
Copy link
Author

Bonus: if you want to return the current day if it is Friday, the if ... block needs to look like this:

if num_days_from_monday < 4 {
    today_naive
        .checked_add_signed(chrono::Duration::days((4 - num_days_from_monday) as _))
        .unwrap()
} else if 4 < num_days_from_monday {
    today_naive
        .checked_add_signed(chrono::Duration::days((11 - num_days_from_monday) as _))
        .unwrap()
} else {
    today_naive
}
    

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment