没有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不迷路!!

相关推荐
C嘎嘎嵌入式开发2 小时前
(2)100天python从入门到拿捏
开发语言·python
Stanford_11063 小时前
如何利用Python进行数据分析与可视化的具体操作指南
开发语言·c++·python·微信小程序·微信公众平台·twitter·微信开放平台
Vallelonga3 小时前
Rust 中的数组和数组切片引用
开发语言·rust
Kiri霧3 小时前
Rust模式匹配详解
开发语言·windows·rust
white-persist4 小时前
Python实例方法与Python类的构造方法全解析
开发语言·前端·python·原型模式
千里马-horse4 小时前
Async++ 源码分析8--partitioner.h
开发语言·c++·async++·partitioner
Lucis__5 小时前
再探类&对象——C++入门进阶
开发语言·c++
007php0075 小时前
某大厂跳动面试:计算机网络相关问题解析与总结
java·开发语言·学习·计算机网络·mysql·面试·职场和发展
你的人类朋友5 小时前
先用js快速开发,后续引入ts是否是一个好的实践?
前端·javascript·后端
码事漫谈6 小时前
医疗设备控制系统中同步与异步通信的架构设计
后端