chrono
chrono copied to clipboard
Support defaulting to zero minutes/hours/seconds
extern crate chrono;
use chrono::NaiveDateTime;
fn main() {
println!("{}:", 1);
if let Err(e) = NaiveDateTime::parse_from_str("2019010101", "%Y%m%d%H") {
println!("{}", e);
}
println!("{}:", 2);
if let Err(e) = NaiveDateTime::parse_from_str("201901010100", "%Y%m%d%H%M") {
println!("{}", e);
}
}
output:
1:
input is not enough for unique date and time
2:
Why not just treat missing field as zero
There are a couple open questions about the best way to do this, I think:
- add another method like
parse_from_str_default(tstr, fmtstr, DefaultTime)with an enum likeenum DafaultTime { Beginning, End }, which will also allow us to default to the max time, although I'm not sure who needs that. Advantage: I think this is the most convenient api. - Add a method to parseresult that will allow selecting beginning or end possible values, if the only problem is not unique. Advantage: This corresponds to what needs to happen for ambiguous (due to DST/leap second changes) anyway.
- add another method like
parse_from_str_partial(tstr, fmtstr) -> TimestampFieldswhere the timestamp fields containsOption<u8>for most fields. While verbose, this will allow building with something like DateTime::from_ymd(fields.year.unwrap_or(1970), fields.month.unwrap_or(..), ..etc)`. Advantage: this is the most flexible.
I'd like something similar for NaiveDate, to default month/day to 1 if they are not given. I'm trying to deserialize a date field from a json API which sometimes returns just a year. Or maybe it would make sense to make a new type, like LaxDate/LaxDateTime or PartialDate/PartialDateTime? NaiveDateTimeWithDefaults? I dunno, maybe someone has a better idea?