-
Notifications
You must be signed in to change notification settings - Fork 553
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
Leap year and last day of month #29
Comments
While Chrono is inherently tied to the proleptic Gregorian calendar, I don't think such specific functions are not a good fit for general purpose library. If you only care about the correct answer (and not the performance), the following can be used:
I think JodaTime does have methods like |
You can add this functionality for your project with: trait NaiveDateExt {
fn days_in_month(&self) -> i32;
fn days_in_year(&self) -> i32;
fn is_leap_year(&self) -> bool;
}
impl NaiveDateExt for chrono::NaiveDate {
fn days_in_month(&self) -> i32 {
let month = self.month();
match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 => if self.is_leap_year() { 29 } else { 28 },
_ => panic!("Invalid month: {}" , month),
}
}
fn days_in_year(&self) -> i32 {
if self.is_leap_year() { 366 } else { 365 }
}
fn is_leap_year(&self) -> bool {
let year = self.year();
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
}
} |
I apologize for necroposting, but could you explain why? A safe variation of the pub fn last_of_month(year: i32, month: u32) -> Option<chrono::NaiveDate> {
chrono::NaiveDate::from_ymd_opt(year, month + 1, 1)
.or_else(|| chrono::NaiveDate::from_ymd_opt(year + 1, 1, 1))?
.pred_opt()
} |
I have seen this request more than once, and I also think it is reasonable and useful to add. #1247 includes I am not sure yet about the best API for something like |
Would you mind adding something like:
?
Thanks.
The text was updated successfully, but these errors were encountered: