How to Find the time difference between two chorno::NaiveDateTime and turn it into seconds

Expected final behaviour

has 2 NaiveDateTime object* in memory,1 is in the future and another is current time.
find the difference in time as second unit into u64.

  • After hours of research ,trial and error below is the partial* working code I have.It only does get the time difference but it seems to ignore the date,and also seems to be going negative?

//where the date_only and alarm_time is parsed from std::env::args
let mut trgtdt = NaiveDateTime::new(date_only,alarm_time);
println!("{}",(trgtdt-chrono::offset::Local::now().naive_local()).num_seconds().to_string());//test use
sleep_seconds = (trgtdt-chrono::offset::Local::now().naive_local()).num_seconds();
return sleep_seconds as u64;

1 Like

How about this?

fn naive_abs_diff_seconds(t1: NaiveDateTime, t2: NaiveDateTime) -> u64 {
    (t2 - t1).num_seconds().unsigned_abs()

This does resolve the negative problem but I later found the actual logic in this code doesnt work,it kinda gives a false positive value.
instead i used signed_duration_since

What do you mean, exactly? The documentation of NaiveDateTime::sub() explicitly mentions that it's implemented in terms of signed_duration_since(). Hence, it's simply not possible that my solution doesn't give the same result as signed_duration_since().

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.