From f5a4331d0adf7b5df221ae3f27fa7be84cf2938a Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 3 Oct 2019 14:53:00 +0200 Subject: [PATCH] Add helper function to parse string by several datetime formats Signed-off-by: Matthias Beyer --- lib/etc/libimagutil/src/date.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/lib/etc/libimagutil/src/date.rs b/lib/etc/libimagutil/src/date.rs index dc9b7745..9ea5a4de 100644 --- a/lib/etc/libimagutil/src/date.rs +++ b/lib/etc/libimagutil/src/date.rs @@ -45,3 +45,28 @@ pub fn datetime_from_string(s: S) -> Result NaiveDateTime::parse_from_str(s.as_ref(), NAIVE_DATETIME_STRING_FORMAT) } +/// Try to parse `s` with all formats from `fmts` +/// +/// The function returns an `Option`, so that the user of the function can generate +/// the appropriate error message themselves. +/// +pub fn try_to_parse_datetime_from_string<'a, S, Formats, Format>(s: S, fmts: Formats) -> Option + where S: AsRef, + Formats: Iterator, + Format: AsRef +{ + fmts.fold(None, |a, f| a.or_else(|| NaiveDateTime::parse_from_str(s.as_ref(), f.as_ref()).ok())) +} + +#[test] +fn test_try_to_parse_datetime_from_string() { + let formats = vec![ + "%Y%m%dT%H%M%S", + "%Y%m%dT%H%M%SZ" + ]; + + let text = "20190730T160527Z"; + + assert!(try_to_parse_datetime_from_string(text, formats.iter()).is_some()) +} +