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?
}
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.
To easily convert UNIX timestamp to date in the . csv file, do the following: 1. =R2/86400000+DATE(1970,1,1), press Enter key.
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
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))
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With