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

相关推荐
趣知岛2 分钟前
Java反射和设计模式
java·开发语言·设计模式·反射
Hello eveybody4 分钟前
C++四级考试要点
开发语言·c++
期待のcode10 分钟前
Java中的this关键字
java·开发语言
异界蜉蝣11 分钟前
Proxy vs Object.defineProperty:Vue3响应式原理的深度革命
开发语言·前端·javascript
谅望者15 分钟前
数据分析笔记15:Python模块、包与异常处理
开发语言·人工智能·python
九月生19 分钟前
Rust CLI 项目构建指南
rust
黎雁·泠崖21 分钟前
C 语言联合体与枚举:共用内存 + 常量枚举 + 实战
c语言·开发语言·python
yousuotu22 分钟前
基于Python实现亚马逊销售数据分析与预测
开发语言·python·数据分析
L Jiawen22 分钟前
【Golang基础】基础知识(上)
开发语言·后端·golang
张登杰踩25 分钟前
django后台管理配置教程
后端·python·django