Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
cecton opened this issue Feb 19, 2024 · 3 comments
Open

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

cecton opened this issue Feb 19, 2024 · 3 comments

Comments

@cecton
Copy link
Contributor

cecton commented Feb 19, 2024

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()
@pitdicker
Copy link
Collaborator

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

@cecton
Copy link
Contributor Author

cecton commented Feb 19, 2024

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 cecton closed this as completed Feb 19, 2024
@pitdicker
Copy link
Collaborator

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants