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

相关推荐
用户4822137167756 分钟前
C++——访问控制
后端
语落心生16 分钟前
数控技术:数控系统刀补功能的软件实现及其仿真
后端
柯南二号19 分钟前
【Java后端】MyBatis-Plus 原理解析
java·开发语言·mybatis
码码哈哈爱分享22 分钟前
Tauri 框架介绍
css·rust·vue·html
又是努力搬砖的一年27 分钟前
SpringBoot中,接口加解密
java·spring boot·后端
0wioiw037 分钟前
Python基础(Flask①)
后端·python·flask
我是哈哈hh38 分钟前
【Node.js】ECMAScript标准 以及 npm安装
开发语言·前端·javascript·node.js
风象南1 小时前
SpringBoot 自研运行时 SQL 调用树,3 分钟定位慢 SQL!
spring boot·后端
Jenny1 小时前
第九篇:卷积神经网络(CNN)与图像处理
后端·面试
大志说编程1 小时前
LangChain框架入门16:智能客服系统RAG应用实战
后端·langchain·aigc