chronotope / chrono

Date and time library for Rust
Other
3.3k stars 523 forks source link

Proper way to build a DateTime from another DateTime's Date #1508

Closed xguerin closed 6 months ago

xguerin commented 6 months ago

Hello,

I have a use case where I need to build a DateTime from Local::now() using its Date component and some future Time, respecting the timezone. This is trivially done using DateTime::date(), but this function has been deprecated. What would be the recommended way to do this (date_naive() does not work here as it's stripped of the original timezone).

Thanks,

pitdicker commented 6 months ago

Maybe something similar to https://github.com/chronotope/chrono/issues/1447#issuecomment-1952122236?

pitdicker commented 6 months ago
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

As a bit of explanation: Local::now() gets the current time and the current offset from UTC. If you adjust to to a future time the only part you can keep is the date part (.date_naive()). The time is new (in this example midnight), and the offset must be recalculated for the final datetime (Local.from_local_datetime) because during that day it may have switched for example from winter to summer time.

We don't have a more convenient solution (yet).

xguerin commented 6 months ago

Thanks for your response!