I'm using chrono crate
I've got date in i64
and I can get NaiveDateTime
with NaiveDateTime::from_timestamp
I have Local::now()
current time and I can get i64
with .timestamp()
But I still can't understand how to get Duration
of my_time - current_time
because it tells that Sub is not implemented if I try it like that
And if I get diff in i64 timestamps how to convert it into Duration
?
e.g. I want something alike but sub is not implemented there
let uEnd = NaiveDateTime::from_timestamp(end64, 0);
let dtEnd = uEnd.sub(Local::now());
The two date-time types are not compatible, because NaiveDateTime
lacks a time zone. In this case, since you obtained it using NaiveDateTime::from_timestamp
, you can convert it to a DateTime<Utc>
first, and then obtain the difference with signed_duration_since
.
let now = Local::now();
let naive_dt = NaiveDate::from_ymd(2018, 3, 26).and_hms(10, 02, 0);
let other_dt = DateTime::<Utc>::from_utc(naive_dt, Utc);
let diff = now.signed_duration_since(other_dt);
Playground
Future versions of chrono
(after 0.4.1) will support subtracting as an alternative to calling .signed_duration_since
, as long as both operands have the same time zone type. PR #237 Therefore, one will eventually be able to write this:
let diff = now.with_timezone(&Utc) - other_dt;
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