Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created February 9, 2024 22:31
Show Gist options
  • Save fancellu/7475f9ea8249cfad7b275fd8eb3f85e6 to your computer and use it in GitHub Desktop.
Save fancellu/7475f9ea8249cfad7b275fd8eb3f85e6 to your computer and use it in GitHub Desktop.
Rust code to parse dates flexibly with several formats
use chrono::prelude::*;
fn flexi_data_parse(text: &str) -> Option<NaiveDate> {
let text = text.replace(['.', '/'], "-");
let fmts = ["%Y-%m-%d", "%Y-%b-%d", "%d-%b-%Y", "%b-%d-%Y", "%d-%m-%Y"];
for fmt in fmts {
let parser = NaiveDate::parse_from_str(text.as_str(), fmt);
if parser.is_ok() {
return parser.ok();
}
}
None
}
fn main() {
let dates = [
"2010-12-11",
"1999/Mar/02",
"01.Mar.2021",
"Mar.05.2021",
"13/12/1966",
];
for date in dates {
println!("{:?}", flexi_data_parse(date));
}
}
@fancellu
Copy link
Author

fancellu commented Feb 9, 2024

Output

Some(2010-12-11)
Some(1999-03-02)
Some(2021-03-01)
Some(2021-03-05)
Some(1966-12-13)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment