chronotope / chrono

Date and time library for Rust
Other
3.28k stars 518 forks source link

Support defaulting to zero minutes/hours/seconds #330

Open luoq opened 5 years ago

luoq commented 5 years ago
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

quodlibetor commented 4 years ago

There are a couple open questions about the best way to do this, I think:

ccope commented 3 years ago

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?