Last active
February 3, 2023 19:50
-
-
Save juliarose/fc7e36b7894c02e02f846cf7c77ecb31 to your computer and use it in GitHub Desktop.
Next friday at 12pm
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::{Duration, NaiveDate, NaiveDateTime, NaiveTime, Weekday, Datelike}; | |
/// Gets the next day of the week at the given time. If the current date is already the given | |
/// weekday **and** after the given time, it will return the next one. | |
fn get_next_day_of_week_at_time( | |
weekday: Weekday, | |
at_time: NaiveTime, | |
) -> Option<NaiveDateTime> { | |
let mut date = chrono::offset::Local::now(); | |
let one_day = Duration::days(1); | |
// It is currently the weekday we want and after the given time. | |
if date.weekday() == weekday && date.time() > at_time { | |
// Add a day so we scroll over to the next day we're looking for. | |
date = date + one_day; | |
} | |
while date.weekday() != weekday { | |
// Keep adding a day until we reach the day we're looking for. | |
date = date + one_day; | |
} | |
Some(NaiveDate::from_ymd_opt( | |
date.year(), | |
date.month(), | |
date.day(), | |
)?.and_time(at_time)) | |
} | |
fn main() { | |
let time = NaiveTime::from_hms_opt(12, 0, 0).unwrap(); | |
let next_friday_at_12pm = get_next_day_of_week_at_time(Weekday::Fri, time); | |
println!("{next_friday_at_12pm:?}"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment