How to convert timestamp into datetime in a rust canister?

this runs perfect local.
but not ok when running in wasm code on ic replica.

use chrono::{DateTime, Utc};
use std::time::{Duration, UNIX_EPOCH};

pub fn timestamp_to_date(timestamp_ns: u64) -> DateTime<Utc> {
  let timestamp_s = timestamp_ns / 1_000_000_000; // convert to seconds
  let nanos = (timestamp_ns % 1_000_000_000) as u32; // get remaining nanoseconds
  let duration = Duration::new(timestamp_s, nanos);
  let datetime = UNIX_EPOCH + duration;
  DateTime::<Utc>::from(datetime)
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn test_timestamp_to_date() {
    let timestamp_ns = 1708236479191334820;
    let date = timestamp_to_date(timestamp_ns);
    println!("{}", date);
    assert_eq!(date.to_string(), "2024-02-18 10:14:39.191334820 UTC");
  }
}

// cargo test test_timestamp_to_date -- --nocapture  
//err:   run `dfx deploy backend`
//   Failed during wasm installation call: The replica returned a replica error:   
//reject code CanisterError, reject message Wasm module of canister bkyz2-fmaaa-aaaaa-qaaaq-cai is  
//not valid: Wasm module has an invalid import section.   
//Module imports function '__wbindgen_describe' from '__wbindgen_placeholder__' that is not exported  
//by the runtime., error code None  

Great thanks to @oepnchat
Solved by learning from openchat codebase:

use time::OffsetDateTime;
pub fn timestamp_to_date(timestamp_ns: u64) -> String {
//ic_cdk::api::time() returns ns of timestamp
  let timestamp_s = timestamp_ns / 1_000_000_000;
// core funtion here : from_unix_timestamp()
  let date = OffsetDateTime::from_unix_timestamp(timestamp_s as i64).unwrap();
  format!(
    "{:04}_{:02}_{:02}_{:02}_{:02}_{:02}",
    date.year(),
    date.month()as u32,
    date.day(),
    date.hour(),
    date.minute(),
    date.second()
  )
}
//return example:  2024_02_18_06_07_59
1 Like