chrono icon indicating copy to clipboard operation
chrono copied to clipboard

Is there a simpler way to get the current date at a specific time?

Open cecton opened this issue 5 months ago • 3 comments

I was wondering if there is a more idiomatic way to retrieve a date like "today at 00:00"?

This is what I have come up with but it's full of unwrap():

Local.from_local_datetime(&Local::now().date_naive().and_hms_opt(0, 0, 0).unwrap()).unwrap()

cecton avatar Feb 19 '24 09:02 cecton

I am afraid that is pretty much it.

let today = Local::now().date_naive();
let midnight = NaiveTime::MIN;
let today_at_midnight = Local.from_local_datetime(today.and_time(midnight)).unwrap(); // or handle the result

pitdicker avatar Feb 19 '24 10:02 pitdicker

Thank you!! The tip with NaiveTime::MIN is neat, it can remove one of the unwrap().

In the end I made this helper because I use that pattern a lot, especially for 00:00.

pub trait TimeZoneExt: TimeZone {
    fn today_at(&self, hour: u32, min: u32, sec: u32) -> Option<DateTime<Self>>;
}

impl TimeZoneExt for Local {
    fn today_at(&self, hour: u32, min: u32, sec: u32) -> Option<DateTime<Local>> {
        Local
            .from_local_datetime(&Local::now().date_naive().and_hms_opt(hour, min, sec)?)
            .single()
    }
}

If you are interested to get this in the API of chrono please let me know and I will make a PR. (Adapted to use NaiveTime probably)

cecton avatar Feb 19 '24 11:02 cecton

I am hoping to have DateTime::set_time at some point. Then you can write Local::now().set_time(NaiveTime::MIN).unwrap(). That also takes care of one remaining panic case from #1047 that I don't have a workaround for.

I'll leave this issue open though. Maybe today_at is a useful convenience method for Local to have.

pitdicker avatar Feb 19 '24 11:02 pitdicker