view src/util.rs @ 34:9966460e2930

Encapsulate GeoJSON and parse_flexible_timestamp
author Lewin Bormann <lbo@spheniscida.de>
date Thu, 03 Dec 2020 07:51:38 +0100
parents
children 08b4f7127980
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
}