【问题标题】:How to convert Unix time / time since the epoch to standard date and time?如何将自纪元以来的 Unix 时间/时间转换为标准日期和时间?
【发布时间】:2017-07-23 03:55:54
【问题描述】:

我正在使用chrono crate;经过一番挖掘,我发现DateTime 类型有一个函数timestamp(),它可以生成i64 类型的纪元时间。但是,我不知道如何将其转换回DateTime

extern crate chrono;
use chrono::*;

fn main() {
    let date = chrono::UTC.ymd(2020, 1, 1).and_hms(0, 0, 0);
    println!("{}", start_date.timestamp());
    // ...how to convert it back?
}

【问题讨论】:

    标签: time rust rust-chrono


    【解决方案1】:

    您首先需要创建一个NaiveDateTime,然后使用它再次创建一个DateTime

    extern crate chrono;
    use chrono::prelude::*;
    
    fn main() {
        let datetime = Utc.ymd(2020, 1, 1).and_hms(0, 0, 0);
        let timestamp = datetime.timestamp();
        let naive_datetime = NaiveDateTime::from_timestamp(timestamp, 0);
        let datetime_again: DateTime<Utc> = DateTime::from_utc(naive_datetime, Utc);
    
        println!("{}", datetime_again);
    }
    

    Playground

    【讨论】:

    【解决方案2】:

    您可以使用parse_duration crate:https://docs.rs/parse_duration/2.1.0/parse_duration/

    extern crate parse_duration;
    use parse_duration::parse;
    use std::time::Duration;
    
    fn main() {
        // 1587971749 seconds since UNIX_EPOCH
        assert_eq!(parse("1587971749"), Ok(Duration::new(1587971749, 0)));
    
        // One hour less than a day
        assert_eq!(parse("1 day -1 hour"), Ok(Duration::new(82_800, 0)));
    
        // Using exponents
        assert_eq!(
            parse("1.26e-1 days"),
            Ok(Duration::new(10_886, 400_000_000))
        );
    
        // Extra things will be ignored
        assert_eq!(
            parse("Duration: 1 hour, 15 minutes and 29 seconds"),
            Ok(Duration::new(4529, 0))
        );
    }
    

    【讨论】:

      【解决方案3】:

      不确定我是否遗漏了什么,或者 chrono 在此期间扩展了它的功能集,但它是 2021 年,至少从 chrono 0.4.0 开始,似乎有一种更简洁的方法:

      https://docs.rs/chrono/0.4.19/chrono/#conversion-from-and-to-epoch-timestamps

      use chrono::{DateTime, TimeZone, Utc};
      
      // Construct a datetime from epoch:
      let dt = Utc.timestamp(1_500_000_000, 0);
      assert_eq!(dt.to_rfc2822(), "Fri, 14 Jul 2017 02:40:00 +0000");
      
      // Get epoch value from a datetime:
      let dt = DateTime::parse_from_rfc2822("Fri, 14 Jul 2017 02:40:00 +0000").unwrap();
      assert_eq!(dt.timestamp(), 1_500_000_000);
      

      所以你的完整转换应该是这样的:

      extern crate chrono;
      use chrono::*;
      
      fn main() {
          let start_date = chrono::Utc.ymd(2020, 1, 1).and_hms(0, 0, 0);
          let ts = start_date.timestamp();
          println!("{}", &ts);
          let end_date = Utc.timestamp(ts, 0);
          assert_eq!(end_date, start_date);
      }
      

      【讨论】:

        猜你喜欢
        • 2018-12-27
        • 2011-07-25
        • 2013-01-08
        • 1970-01-01
        • 2016-01-21
        • 2020-04-24
        • 2016-09-15
        • 2018-08-03
        相关资源
        最近更新 更多