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

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

Closed
xguerin opened this issue Mar 11, 2024 · 3 comments
Closed

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

xguerin opened this issue Mar 11, 2024 · 3 comments

Comments

@xguerin
Copy link

xguerin commented Mar 11, 2024

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,

@xguerin xguerin changed the title Proper way to build a DateTime from another DateTime's date Proper way to build a DateTime from another DateTime's Date Mar 11, 2024
@pitdicker
Copy link
Collaborator

Maybe something similar to #1447 (comment)?

@pitdicker
Copy link
Collaborator

pitdicker commented Mar 11, 2024

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
Copy link
Author

xguerin commented Mar 12, 2024

Thanks for your response!

@xguerin xguerin closed this as completed Mar 12, 2024
@djc djc reopened this Mar 12, 2024
@djc djc closed this as not planned Won't fix, can't repro, duplicate, stale Mar 12, 2024
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

3 participants