我正在尝试创建一个日期选择器,我需要在几个月之间导航
let current = NaiveDate::parse_from_str("2020-10-15", "%Y-%m-%d").unwrap();
Run Code Online (Sandbox Code Playgroud)
我怎样才能生成日期2020-11-15?
这是我的解决方案:
use chrono::{ NaiveDate, Duration, Datelike};
fn get_days_from_month(year: i32, month: u32) -> u32 {
NaiveDate::from_ymd(
match month {
12 => year + 1,
_ => year,
},
match month {
12 => 1,
_ => month + 1,
},
1,
)
.signed_duration_since(NaiveDate::from_ymd(year, month, 1))
.num_days() as u32
}
fn add_months(date: NaiveDate, num_months: u32) -> NaiveDate {
let mut month = date.month() + num_months;
let year = date.year() + (month / 12) as i32;
month = month % 12;
let mut day = date.day();
let max_days = get_days_from_month(year, month);
day = if day > max_days { max_days } else { day };
NaiveDate::from_ymd(year, month, day)
}
fn main() {
let date = NaiveDate::parse_from_str("2020-10-31", "%Y-%m-%d").unwrap();
let new_date = add_months(date, 4);
println!("{:?}", new_date);
}
Run Code Online (Sandbox Code Playgroud)
NaiveDate现在有一个方法checked_add_months
assert_eq!(
NaiveDate::from_ymd(2020, 10, 15).checked_add_months(chrono::Months::new(1)),
Some(NaiveDate::from_ymd(2020, 11, 15))
);
assert_eq!(
NaiveDate::from_ymd(2020, 10, 15).checked_add_months(chrono::Months::new(3)),
Some(NaiveDate::from_ymd(2021, 1, 15))
);
Run Code Online (Sandbox Code Playgroud)