Last active
April 19, 2022 12:12
-
-
Save virtualritz/585c80b0eb866d1047b719b2d2365463 to your computer and use it in GitHub Desktop.
Find the next Friday from today in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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,); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Bonus: if you want to return the current day if it is Friday, the
if ...
block needs to look like this: