nushell/crates/nu-command/src/date/utils.rs
Jonathan Moore ef70c8dbe4
Date parse refactor (#4661)
* More flexible and DRY datetime parsing

* Update error messages

* cargo fmt

* clippy

* Add DatetimeParseError
2022-02-27 20:21:46 -05:00

27 lines
889 B
Rust

use chrono::{DateTime, FixedOffset, Local, LocalResult, TimeZone};
use nu_protocol::{ShellError, Span, Value};
pub(crate) fn parse_date_from_string(
input: &str,
span: Span,
) -> Result<DateTime<FixedOffset>, Value> {
match dtparse::parse(input) {
Ok((native_dt, fixed_offset)) => {
let offset = match fixed_offset {
Some(fo) => fo,
None => *(Local::now().offset()),
};
match offset.from_local_datetime(&native_dt) {
LocalResult::Single(d) => Ok(d),
LocalResult::Ambiguous(d, _) => Ok(d),
LocalResult::None => Err(Value::Error {
error: ShellError::DatetimeParseError(span),
}),
}
}
Err(_) => Err(Value::Error {
error: ShellError::DatetimeParseError(span),
}),
}
}