chrono icon indicating copy to clipboard operation
chrono copied to clipboard

Support defaulting to zero minutes/hours/seconds

Open luoq opened this issue 6 years ago • 2 comments

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

luoq avatar Aug 12 '19 06:08 luoq

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 like enum 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) -> TimestampFields where the timestamp fields contains Option<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.

quodlibetor avatar Jan 04 '20 21:01 quodlibetor

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?

ccope avatar May 11 '21 01:05 ccope