Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
}
like image 539
Sajuuk Avatar asked Mar 03 '17 06:03

Sajuuk


People also ask

How do I convert epoch time to normal date?

Convert from epoch to human-readable dateString date = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new java.util.Date (epoch*1000)); Epoch in seconds, remove '*1000' for milliseconds. myString := DateTimeToStr(UnixToDateTime(Epoch)); Where Epoch is a signed integer. Replace 1526357743 with epoch.

How do I convert Unix time to normal time?

To easily convert UNIX timestamp to date in the . csv file, do the following: 1. =R2/86400000+DATE(1970,1,1), press Enter key.


2 Answers

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

like image 146
ljedrz Avatar answered Nov 02 '22 21:11

ljedrz


You can use the 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))
    );
}
like image 20
user Avatar answered Nov 02 '22 23:11

user