没有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. 使用 PartialOrd 和 Ord trait 结合 PartialEq 和 Eq 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");
    }
}

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

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

相关推荐
Wang's Blog4 分钟前
Java 项目实战:交友项目 - 我的访客:需求说明
java·开发语言·交友
贾公子23 分钟前
检测结果怎么落库——表结构、状态机与三类对账
后端·mysql
布莱克60525 分钟前
C++ 中堆和栈的区别详解
开发语言·c++·栈·堆
像风一样自由202036 分钟前
3.Dockerfile如何构建一个Python算法镜像
开发语言·人工智能·python·大模型
1360967572341 分钟前
LLM 当裁判可靠吗:位置偏见、长度偏见、自我偏好
后端
拖孩1 小时前
流量主门槛从 500 降到 100,我的小程序上线 18 小时够到了线
前端·后端·微信小程序
养军博客1 小时前
Spring Security 4.x / 5.x / 6.x 配置全对比:前后端不分离与前后端分离
java·后端·spring·springsecurity
wifi___1 小时前
SpringBoot自动装配原理
java·spring boot·后端
日日大王学编程1 小时前
AI 时代后端方向新人的未来规划与看法
人工智能·后端·python·ai·golang
Fox爱分享2 小时前
都问程序员双十一买什么,我的答案一定是这块专业编程显示器
后端·程序员·ai编程