Rust编程:使用chrono处理日期时间

2023-08-1110:08:26编程语言入门到精通Comments3,197 views字数 4978阅读模式

chrono旨在成为时间库的一个功能完整的超集。它严格遵守ISO 8601,默认包含时区,也有不含时区的类型。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/53609.html

1,先来一个小点心,测量函数耗费时间,使用的标准库time。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/53609.html
use std::thread;use std::time::{Duration, Instant};fn expensive_function() {    thread::sleep(Duration::from_secs(1));}fn main() {    let start = Instant::now();    expensive_function();    let duration = start.elapsed();    println!("Time elapsed in expensive_function() is: {:?}", duration);}// 打印结果Time elapsed in expensive_function() is: 1.0122099s

2,获取当前时间文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/53609.html

use chrono::prelude::*;
let utc: DateTime<Utc> = Utc::now(); // e.g. `2014-11-28T12:45:59.324310806Z`let local: DateTime<Local> = Local::now(); // e.g. `2014-11-28T21:45:59.324310806+09:00`println!("the utc is {},the local is {}", utc, local);// 打印结果the utc is 2023-07-01 01:50:40.050821800 UTC,the local is 2023-07-01 09:50:40.050837400 +08:00

3,日期计算,计算1周后,3天前等。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/53609.html

use chrono::{Duration, Local};fn main() {    let now = Local::now();    println!("{}", now);    let after_one_week = now.checked_add_signed(Duration::weeks(1)).unwrap();    let three_day_earlier = now.checked_sub_signed(Duration::days(3)).unwrap();    println!(        "now is {},now after one week is {},and now before three days is {}.",        now, after_one_week, three_day_earlier    );}
// 打印结果now is 2023-07-01 09:54:01.195332500 +08:00,now after one week is 2023-07-08 09:54:01.195332500 +08:00,and now before three days is 2023-06-28 09:54:01.195332500 +08:00.

4,日期和时间戳相互转换文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/53609.html

use chrono::{DateTime, TimeZone, Utc};fn main() {    // 时间戳转为日期    let dt = Utc.timestamp_opt(1_500_000_000, 0).unwrap();    println!("the date is {}.", dt.to_rfc2822());
    // 日期转为时间戳    let dt = DateTime::parse_from_rfc2822("Fri, 14 Jul 2017 02:40:00 +0000").unwrap();    println!("the timestamp is {}.", dt.timestamp());}
// 打印结果the date is Fri, 14 Jul 2017 02:40:00 +0000.the timestamp is 1500000000.

5,日期格式化文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/53609.html

use chrono::{DateTime, Local, Utc};fn main() {    let now: DateTime<Utc> = Utc::now();    println!("UTC now is: {}", now);    println!("UTC now in RFC 2822 is: {}", now.to_rfc2822());    println!("UTC now in RFC 3339 is: {}", now.to_rfc3339());    println!(        "UTC now in a custom format is: {}",        now.format("%a %b %e %T %Y")    );    println!(        "UTC now in a custom format is: {}",        now.format("%Y-%m-%d %H:%M:%S")    );
    let now = Local::now();    println!("Local now is: {}", now);    println!("Local now in RFC 2822 is: {}", now.to_rfc2822());    println!("Local now in RFC 3339 is: {}", now.to_rfc3339());    println!(        "Local now in a custom format is: {}",        now.format("%a %b %e %T %Y")    );    println!(        "Local now in a custom format is: {}",        now.format("%Y-%m-%d %H:%M:%S")    );}
// 打印结果UTC now is: 2023-07-01 02:12:41.864372800 UTCUTC now in RFC 2822 is: Sat, 01 Jul 2023 02:12:41 +0000UTC now in RFC 3339 is: 2023-07-01T02:12:41.864372800+00:00UTC now in a custom format is: Sat Jul  1 02:12:41 2023UTC now in a custom format is: 2023-07-01 02:12:41Local now is: 2023-07-01 10:12:41.865922200 +08:00Local now in RFC 2822 is: Sat, 01 Jul 2023 10:12:41 +0800Local now in RFC 3339 is: 2023-07-01T10:12:41.865922200+08:00Local now in a custom format is: Sat Jul  1 10:12:41 2023Local now in a custom format is: 2023-07-01 10:12:41

6,字符串转为日期文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/53609.html

use chrono::format::ParseError;use chrono::{DateTime, FixedOffset, TimeZone, Utc};fn main() -> Result<(), ParseError> {    // 方法1    let date1 = "2014-11-28T12:00:09Z".parse::<DateTime<Utc>>().unwrap();    println!("date1 is {}.", date1);    let date2 = "2014-11-28T21:00:09+09:00"        .parse::<DateTime<Utc>>()        .unwrap();    println!("date2 is {}.", date2);    let date3 = "2014-11-28T21:00:09+09:00"        .parse::<DateTime<FixedOffset>>()        .unwrap();    println!("date3 is {}.", date3);    // 方法2    let date1 =        DateTime::parse_from_str("2014-11-28 21:00:09 +09:00", "%Y-%m-%d %H:%M:%S %z").unwrap();    println!("date1 is {}.", date1);    let date2 = DateTime::parse_from_rfc2822("Fri, 28 Nov 2014 21:00:09 +0900").unwrap();    println!("date2 is {}.", date2);    let date3 = DateTime::parse_from_rfc3339("2014-11-28T21:00:09+09:00").unwrap();    println!("date3 is {}.", date3);    // 方法3    let date1 = Utc        .datetime_from_str("2014-11-28 12:00:09", "%Y-%m-%d %H:%M:%S")        .unwrap();    println!("date1 is {}.", date1);    let date2 = Utc        .datetime_from_str("Fri Nov 28 12:00:09 2014", "%a %b %e %T %Y")        .unwrap();    println!("date2 is {}.", date2);    Ok(())}
// 打印结果date1 is 2014-11-28 12:00:09 UTC.date2 is 2014-11-28 12:00:09 UTC.date3 is 2014-11-28 21:00:09 +09:00.date1 is 2014-11-28 21:00:09 +09:00.date2 is 2014-11-28 21:00:09 +09:00.date3 is 2014-11-28 21:00:09 +09:00.date1 is 2014-11-28 12:00:09 UTC.date2 is 2014-11-28 12:00:09 UTC.

7,获取日期的年月日和时分秒等信息文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/53609.html

use chrono::{Datelike, FixedOffset, NaiveDate, TimeZone, Timelike};fn main() {    let now = FixedOffset::east_opt(9 * 3600)        .unwrap()        .from_local_datetime(            &NaiveDate::from_ymd_opt(2014, 11, 28)                .unwrap()                .and_hms_nano_opt(21, 45, 59, 324310806)                .unwrap(),        )        .unwrap();    println!("now is {}.", now);    // 获取时分秒    let (is_pm, hour) = now.hour12();    println!(        "The current time is {:02}:{:02}:{:02} {}",        hour,        now.minute(),        now.second(),        if is_pm { "PM" } else { "AM" }    );    println!(        "And there have been {} seconds since midnight",        now.num_seconds_from_midnight()    );    let (is_common_era, year) = now.year_ce();    println!(        "The current date is {}-{:02}-{:02} {:?} ({})",        year,        now.month(),        now.day(),        now.weekday(),        if is_common_era { "CE" } else { "BCE" }    );    println!(        "The week of year is {:?},and the day of year is {}",        now.iso_week(),        now.ordinal(),    );    println!(        "And the Common Era began {} days ago",        now.num_days_from_ce()    );}
// 打印结果now is 2014-11-28 21:45:59.324310806 +09:00.The current time is 09:45:59 PMAnd there have been 78359 seconds since midnightThe current date is 2014-11-28 Fri (CE)The week of year is 2014-W48,and the day of year is 332And the Common Era began 735565 days ago

更多内容请查看https://docs.rs/chrono/0.4.26/chrono/文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/53609.html

文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/53609.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/ymba/53609.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定