date - 如何获得两个计时日期之间的差异?
问题描述
我想得到今天08/11/2020
和01/01/1970
这种格式之间的“时间跨度”差异:
Timespan:
50 year(s) 10 month(s) 7 day(s)
下面的代码正确地计算了这个:today - 01/01/1970
。23/12/1970
但是,对于像给予这样的输入,它却惨遭失败:
50 year(s) -1 month(s) -15 day(s)
而预期的结果是49 year(s) 10 month(s) 16 day(s)
。
更多测试日期:
09/01/1985
得到:
35 year(s) 10 month(s) -1 day(s)
但预期35 year(s) 9 month(s) 30 day(s)
。24/02/1936
得到:
84 year(s) 9 month(s) -16 day(s)
但预期84 year(s) 8 month(s) 15 day(s)
。
货物.toml:
[package]
name = "relative-delta"
version = "0.1.0"
authors = ["baduker"]
edition = "2018"
[dependencies]
chrono = "0.4.19"
代码:
use chrono::{NaiveDateTime, DateTime, Utc, Datelike};
fn main() {
let date_string = "23/12/1970";
let naive_date = chrono::NaiveDate::parse_from_str(date_string, "%d/%m/%Y").unwrap();
let naive_datetime: NaiveDateTime = naive_date.and_hms(0, 0, 0);
let date = DateTime::<Utc>::from_utc(naive_datetime, Utc);
let years = Utc::now().year() - date.year();
let months = Utc::now().month() as i64 - date.month() as i64;
let days = Utc::now().day() as i64 - date.day() as i64;
println!("Timespan:\n{} year(s) {} month(s) {} day(s)", years, months, days);
}
解决方案
您的计算对我没有意义,例如,如果今天的日期是 2021 年 11 月 1 日,您的计算将返回 1 - 23 = -22 作为天数。今天是我学习 Rust 的第三天,因此我没有足够的专业知识来为您提供优化的解决方案。但是,如果假设一年是 365 天,一个月是 30 天,那么下面的解决方案应该可以满足您的要求。
use chrono::{DateTime, Utc};
fn main() {
// Tests
print_diff("23/12/1970");
}
fn print_diff(date_string: &str) {
let today = Utc::now();
let datetime =
DateTime::<Utc>::from_utc(chrono::NaiveDate::parse_from_str(date_string, "%d/%m/%Y")
.unwrap()
.and_hms(0, 0, 0), Utc);
let diff = today.signed_duration_since(datetime);
let days = diff.num_days();
let years = days / 365;
let remaining_days = days % 365;
let months = remaining_days / 30;
let days = remaining_days % 30;
println!("{} years {} months {} days", years, months, days);
}
输出:
50 years 11 months 9 days
推荐阅读
- c++ - C++ 枚举类作为可变模板参数
- sql - 如何使用 DML 命令从两个不同的表中更新表中的列
- c++ - 错误:我的班级的“操作员>>”不匹配
- vb.net - 从文本中读取文件并创建循环
- tensorflow - 如何使用 TensorFlow 2 自定义 CNN 层,在 CNN 的密集层提供新输入
- javascript - 未捕获的类型错误:无法读取创建的 VueJ 中未定义的属性“0”
- php - 用户提交收据后删除购物车中的项目
- python - Python通过循环登录不同的帐户
- symfony - Symfony“fos_rest.request_body”转换器:不要反序列化嵌套的 DTO 类
- javascript - addEventListener 加载在 Firefox 上触发两次