[chrono] 'No such local time' - How to do error handling?

I have a problem with conversion milliseconds to DataTime.
When the value is incorrect then the program crash.
IMHO Function Utc.timestamp_millis(...) should return Result<T> or Option<T> for safe.
How to do error handling?

  let millis : i64 = 578437695752307201 as i64;
  let data_time = Utc.timestamp_millis(millis);


thread 'main' panicked at 'No such local time', /playground/.cargo/registry/src/github.com-1ecc6299db9ec823/chrono-0.4.19/src/offset/mod.rs:173:34

Please check: Playground

If you want a version that returns a Result-like thing you can handle, you can use timestamp_millis_opt(). timestamp_millis() just calls timestamp_millis_opt() and unwraps the result. Note that timestamp_millis_opt() actually returns a chrono::offset::LocalResult, which handles the possiblility that there could be an ambiguous range of times corresponding to the given value, but it has many similar methods to Result and Option, and it is also an enum you can match on.

@jameseb7 thx for your reply.

I did solve it: Playground


match Utc.timestamp_millis_opt(millis)
   LocalResult::Single(dt) => { println!("milis: {} = {}", millis, dt); },
   LocalResult::Ambiguous(dt, dt2) => { println!("Ambiguous milis: {} = {}/{}", millis, dt, dt2); },
   LocalResult::None => { println!("Error"); }
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.