I've been banging my head against the time crate for the last two days. I can't find, where in their documentation how to take a RFC3339 UTC 2022-12-28T02:11:46Z
timestamp and convert that to local time for America/New_York
( 2022-12-27T21:11:46
). I stepped away from using the chrono
crate on advise that there is/was a vulnerability and it's not very well maintained as it once was. Chrono
also depends on time
but in the 0.1.x
branch of it.
My cargo.toml includes the line time = { version = "0.3", features = ["macros", "parsing", "local-offset"] }
so enable the features I think I need.
use time::{format_description::well_known::Rfc3339, PrimitiveDateTime};
/// The paramater zulu would be a RFC3339 formatted string.
///
/// ```
/// #use time::{format_description::well_known::Rfc3339, PrimitiveDateTime};
/// assert_eq!("2022-12-27T21:11:46", date_time_local("2022-12-28T02:11:46Z".to_string()));
/// ```
fn date_time_local(zulu: &String) -> String {
match PrimitiveDateTime::parse(zulu, &Rfc3339) {
Ok(local) => local.to_string(),
Err(..) => zulu.to_owned(),
}
}
I'm having no such luck here.
fn main() {
assert_eq!("2022-12-27 21:11:46", date_time_local(&"2022-12-28T02:11:46Z".to_string()));
}
/// The parameter zulu should be a RFC3339 formatted string.
/// This converts that Zulu timestamp into a local timestamp.
/// ```
/// assert_eq!("2022-12-27 21:11:46", date_time_local("2022-12-28T02:11:46Z".to_string()));
/// ```
fn date_time_local(zulu: &String) -> String {
use time::{format_description::well_known::Rfc3339, PrimitiveDateTime, UtcOffset};
// Determine Local TimeZone
let utc_offset = match UtcOffset::current_local_offset() {
Ok(utc_offset) => utc_offset,
Err(..) => return zulu.to_owned(),
};
// Parse the given zulu paramater.
let zulu_parsed = match PrimitiveDateTime::parse(zulu, &Rfc3339) {
Ok(zulu_parsed) => zulu_parsed.assume_utc(),
Err(..) => return zulu.to_owned(),
};
// Convert zulu to local time offset.
let parsed = zulu_parsed.to_offset(utc_offset);
format!(
"{:04}-{:02}-{:02} {:02}:{:02}:{:02}",
parsed.year(),
parsed.month() as u8,
parsed.day(),
parsed.hour(),
parsed.minute(),
parsed.second()
)
}
With a slight change that I removed the T
between the date and the time.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.