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

How does chrono Duration get number of years or months? #636

Closed
linrongbin16 opened this issue Dec 21, 2021 · 1 comment
Closed

How does chrono Duration get number of years or months? #636

linrongbin16 opened this issue Dec 21, 2021 · 1 comment

Comments

@linrongbin16
Copy link

Hi, I'm quite new to Rust and chrono library.

I checked the https://docs.rs/chrono/0.4.19/chrono/struct.Duration.html, but there's no num_years() or num_months() API in chrono::Duration.

Is there any work around solution for this ?

@msdrigg
Copy link
Contributor

msdrigg commented Dec 22, 2021

Years and months are types that depend on the current time. For example, what should the following print:

let a = Duration::days(365);
println!("{}", a.num_years());

Well, it depends on whether or not the year is a leap year. Similarly, months have a variable number of days.

If you care about this date dependence, it would probably be best to construct Date objects corresponding to the times you are thinking about and then perform the relevant calculations around Date.year and Date.month.

If you just want to know "about how many years in this duration", it would be best to just use Duration.num_days() / 365.

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