Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- extern crate chrono;
- use chrono::{NaiveDate, Datelike};
- fn get_months(start_date_opt: Option<NaiveDate>, end_date_opt: Option<NaiveDate>) -> i64 {
- let mut days_in_month = vec![31,28,31,30,31,30,31,31,30,31,30,31];
- if start_date_opt.is_none() || end_date_opt.is_none() {
- return 0;
- } else {
- if start_date_opt.unwrap() > end_date_opt.unwrap() {
- return 0;
- }
- let start_date_year = start_date_opt.unwrap().year();
- if is_leap_year(start_date_year) {
- days_in_month[1] = 29;
- }
- let end_date_year = end_date_opt.unwrap().year();
- let start_date_month = start_date_opt.unwrap().month();
- let end_date_month = end_date_opt.unwrap().month();
- let start_date_day = start_date_opt.unwrap().day();
- let end_date_day = end_date_opt.unwrap().day();
- let mut no_years = end_date_year - start_date_year;
- let mut no_months = 0;
- if end_date_month < start_date_month {
- no_years -= 1;
- no_months += (12 - start_date_month) + end_date_month;
- } else {
- no_months += end_date_month - start_date_month;
- }
- if end_date_day < start_date_day {
- no_months -= 1;
- }
- if end_date_day > start_date_day && start_date_day != days_in_month[(start_date_month - 1) as usize] {
- no_months += 1;
- }
- (no_years * 12) as i64 + no_months as i64
- }
- }
- fn is_leap_year(year: i32) -> bool {
- return (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0);
- }
- fn main() {
- let st_date = Some(NaiveDate::from_ymd(2019, 2, 27));
- let end_date = Some(NaiveDate::from_ymd(2019, 3, 31));
- println!("{}", get_months(st_date, end_date));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement