Created
February 9, 2024 22:31
-
-
Save fancellu/7475f9ea8249cfad7b275fd8eb3f85e6 to your computer and use it in GitHub Desktop.
Rust code to parse dates flexibly with several formats
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output
Some(2010-12-11)
Some(1999-03-02)
Some(2021-03-01)
Some(2021-03-05)
Some(1966-12-13)