Advertisement
Guest User

Untitled

a guest
Sep 17th, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. extern crate chrono;
  2. use chrono::{NaiveDate, Datelike};
  3.  
  4. fn get_months(start_date_opt: Option<NaiveDate>, end_date_opt: Option<NaiveDate>) -> i64 {
  5. let mut days_in_month = vec![31,28,31,30,31,30,31,31,30,31,30,31];
  6. if start_date_opt.is_none() || end_date_opt.is_none() {
  7. return 0;
  8. } else {
  9. if start_date_opt.unwrap() > end_date_opt.unwrap() {
  10. return 0;
  11. }
  12. let start_date_year = start_date_opt.unwrap().year();
  13. if is_leap_year(start_date_year) {
  14. days_in_month[1] = 29;
  15. }
  16. let end_date_year = end_date_opt.unwrap().year();
  17. let start_date_month = start_date_opt.unwrap().month();
  18. let end_date_month = end_date_opt.unwrap().month();
  19. let start_date_day = start_date_opt.unwrap().day();
  20. let end_date_day = end_date_opt.unwrap().day();
  21. let mut no_years = end_date_year - start_date_year;
  22. let mut no_months = 0;
  23. if end_date_month < start_date_month {
  24. no_years -= 1;
  25. no_months += (12 - start_date_month) + end_date_month;
  26. } else {
  27. no_months += end_date_month - start_date_month;
  28. }
  29. if end_date_day < start_date_day {
  30. no_months -= 1;
  31. }
  32. if end_date_day > start_date_day && start_date_day != days_in_month[(start_date_month - 1) as usize] {
  33. no_months += 1;
  34. }
  35. (no_years * 12) as i64 + no_months as i64
  36. }
  37. }
  38.  
  39. fn is_leap_year(year: i32) -> bool {
  40. return (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0);
  41. }
  42.  
  43. fn main() {
  44. let st_date = Some(NaiveDate::from_ymd(2019, 2, 27));
  45. let end_date = Some(NaiveDate::from_ymd(2019, 3, 31));
  46. println!("{}", get_months(st_date, end_date));
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement