没有jodatime,rust里怎么比较两个日期(时间)的大小呢?

关注我,学习Rust不迷路!!

在 Rust 中,比较两个日期的大小有多种方法。以下是列举的四种常见方法:

1. 使用 PartialOrd trait:

bash 复制代码
use chrono::prelude::*;

fn main() {
    let date1 = NaiveDate::from_ymd(2022, 1, 1);
    let date2 = NaiveDate::from_ymd(2022, 1, 10);
     if date1 < date2 {
        println!("date1 is less than date2");
    } else if date1 > date2 {
        println!("date1 is greater than date2");
    } else {
        println!("date1 is equal to date2");
    }
}

2. 使用 Ord trait:

bash 复制代码
use chrono::prelude::*;

fn main() {
    let date1 = NaiveDate::from_ymd(2022, 1, 1);
    let date2 = NaiveDate::from_ymd(2022, 1, 10);
     match date1.cmp(&date2) {
        std::cmp::Ordering::Less => println!("date1 is less than date2"),
        std::cmp::Ordering::Greater => println!("date1 is greater than date2"),
        std::cmp::Ordering::Equal => println!("date1 is equal to date2"),
    }
}

3. 使用 PartialOrdOrd trait 结合 PartialEqEq trait:

bash 复制代码
use chrono::prelude::*;

fn main() {
    let date1 = NaiveDate::from_ymd(2022, 1, 1);
    let date2 = NaiveDate::from_ymd(2022, 1, 10);
     if date1.eq(&date2) {
        println!("date1 is equal to date2");
    } else if date1.ne(&date2) {
        println!("date1 is not equal to date2");
    } else if date1.lt(&date2) {
        println!("date1 is less than date2");
    } else if date1.le(&date2) {
        println!("date1 is less than or equal to date2");
    } else if date1.gt(&date2) {
        println!("date1 is greater than date2");
    } else if date1.ge(&date2) {
        println!("date1 is greater than or equal to date2");
    }
}

4. 使用 DateTime 类型的 timestamp 进行比较:

bash 复制代码
use chrono::prelude::*;

fn main() {
    let date1 = NaiveDate::from_ymd(2022, 1, 1);
    let date2 = NaiveDate::from_ymd(2022, 1, 10);
     let timestamp1 = date1.and_hms(0, 0, 0).timestamp();
    let timestamp2 = date2.and_hms(0, 0, 0).timestamp();
     if timestamp1 < timestamp2 {
        println!("date1 is less than date2");
    } else if timestamp1 > timestamp2 {
        println!("date1 is greater than date2");
    } else {
        println!("date1 is equal to date2");
    }
}

这些方法中,前两种使用 PartialOrdOrd trait 进行日期比较,第三种结合了 PartialEqEq trait,而第四种方法使用 DateTime 类型的 timestamp 进行比较。

关注我,学习Rust不迷路!!

相关推荐
爬虫程序猿15 小时前
用 Python 给京东商品详情做“全身 CT”——可量产、可扩展的爬虫实战
开发语言·爬虫·python
徐同保16 小时前
tailwindcss暗色主题切换
开发语言·前端·javascript
蓝纹绿茶16 小时前
bash:**:pip:***python: 错误的解释器: 没有那个文件或目录
开发语言·python·pip
云知谷17 小时前
【经典书籍】C++ Primer 第15章类虚函数与多态 “友元、异常和其他高级特性” 精华讲解
c语言·开发语言·c++·软件工程·团队开发
START_GAME17 小时前
深度学习Diffusers:用 DiffusionPipeline 实现图像生成
开发语言·python·深度学习
不爱编程的小九九18 小时前
小九源码-springboot088-宾馆客房管理系统
java·开发语言·spring boot
thinktik18 小时前
AWS EKS安装S3 CSI插件[AWS 海外区]
后端·kubernetes·aws
Evand J18 小时前
【MATLAB例程】到达角度定位(AOA),平面环境多锚点定位(自适应基站数量),动态轨迹使用EKF滤波优化。附代码下载链接
开发语言·matlab·平面·滤波·aoa·到达角度
细节控菜鸡18 小时前
【2025最新】ArcGIS for JS 实现随着时间变化而变化的热力图
开发语言·javascript·arcgis
Pluto_CSND19 小时前
Java实现gRPC双向流通信
java·开发语言·单元测试