view src/util.rs @ 37:08b4f7127980

Encapsulate notification messaging
author Lewin Bormann <lbo@spheniscida.de>
date Thu, 03 Dec 2020 09:35:51 +0100
parents 9966460e2930
children 1edc60154ba9
line wrap: on
line source

use chrono;

use chrono::TimeZone;

/// Parse timestamps flexibly. Without any zone information, UTC is assumed.
pub fn flexible_timestamp_parse(ts: String) -> Option<chrono::DateTime<chrono::Utc>> {
    let fmtstrings = &[
        "%Y-%m-%dT%H:%M:%S%.f%:z",
        "%Y-%m-%dT%H:%M:%S%.fZ",
        "%Y-%m-%d %H:%M:%S%.f",
    ];
    for fs in fmtstrings {
        let (naive, withtz) = (
            chrono::NaiveDateTime::parse_from_str(ts.as_str(), fs).ok(),
            chrono::DateTime::parse_from_str(ts.as_str(), fs).ok(),
        );
        if let Some(p) = withtz {
            return Some(p.with_timezone(&chrono::Utc));
        }
        if let Some(p) = naive {
            let utcd = chrono::Utc.from_utc_datetime(&p);
            return Some(utcd);
        }
    }
    None
}