Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

rust - How to convert Unix time / time since the epoch to standard date and time?

I'm using the chrono crate; after some digging I discovered the DateTime type has a function timestamp() which could generate epoch time of type i64. However, I couldn't find out how to convert it back to 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?
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You first need to create a NaiveDateTime and then use it to create a DateTime again:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...