waltzofpearls / dateparser

Parse dates in commonly used string formats with Rust.
MIT License
41 stars 8 forks source link

`parse` returns datetime with time set to current local time... #16

Closed jqnatividad closed 2 years ago

jqnatividad commented 2 years ago

...when calling parse with a plain date string. For example:

use dateparser::parse;
use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
    let parsed = parse("July 14, 2021")?;
    println!("{:#?}", parsed);
    Ok(())
}

returns a value like 2021-07-14T22:51:35.983216400Z where the time portion happens to be the current local time.

Shouldn't it just return 2021-07-14T00:00:00Z?

Thanks regardless @waltzofpearls !

waltzofpearls commented 2 years ago

Hey @jqnatividad, yes, you are right. Returning 2021-07-14T00:00:00Z aligns with the behavior from Go's dateparse or Python's dateparser. That said, I created this crate while I was working on belt cli tool, and using local time when time is not given in the input (or use local date when date is not given) is the behavior I wanted. I can make it configurable, and default time to 00:00:00.

For the time being, you can change parse() returned Result<DateTime<Utc>> to 2021-07-14 00:00:00 UTC with:

let parsed = dateparser::parse("July 14, 2021")
    .ok()
    .and_then(|dt| dt.with_hour(0))
    .and_then(|dt| dt.with_minute(0))
    .and_then(|dt| dt.with_second(0))
    .map(|dt| dt.trunc_subsecs(0))
    .ok_or_else(|| anyhow::anyhow!("failed parsing date & time input"))?;

println!("{}", parsed)
jqnatividad commented 2 years ago

Thanks @waltzofpearls for the quick reply and the workaround.

I'll use the workaround in the meantime and look forward to the next release!