Chrono - How to convert a bytes to date&time string?

Hello!
How to convert bytes:

let datetime_bytes = vec![60, 146, 149, 126, 123, 1, 0, 0]; 
// unix timestamp with milis 1629916336700 = Wed Aug 25 2021 18:32:16

to string (Data & Time with milis) ?

My code:
Playground

You’ll need to convert the bytes to an i64 first, then use Utc.timestamp_millis to convert that to a Chrono DateTime, and you can format that to the string that you want:

fn to_date_time_string(datetime_bytes: &[u8]) -> String
{
    let millis = i64::from_le_bytes(datetime_bytes.try_into().unwrap());
    let datetime = Utc.timestamp_millis(millis);
    datetime.format("%Y-%m-%d %H:%M:%S.%f").to_string()
}

If you could get the i64 directly then you could skip a step.

1 Like

Thx.

My solution:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=72cae737dd30fd13e772324c7307c2d1

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.