add 'next' and 'last' support

This commit is contained in:
undali
2023-06-26 15:27:05 +04:00
parent bed2d16e67
commit c24d593821
2 changed files with 17 additions and 0 deletions
+1
View File
@@ -58,6 +58,7 @@ The `from_str` and `from_str_at_date` functions support the following formats fo
- "yesterday"
- "tomorrow"
- use "ago" for the past
- use "next" or "last" with `unit` (e.g., "next week", "last year")
- combined units with "and" or "," (e.g., "2 years and 1 month", "1 day, 2 hours" or "2 weeks 1 second")
`num` can be a positive or negative integer.
+16
View File
@@ -124,6 +124,7 @@ pub fn from_str_at_date(date: NaiveDate, s: &str) -> Result<Duration, ParseDurat
let time_pattern: Regex = Regex::new(
r"(?x)
(?:(?P<value>[-+]?\d*)\s*)?
(\s*(?P<direction>next|last)?\s*)?
(?P<unit>years?|months?|fortnights?|weeks?|days?|hours?|h|minutes?|mins?|m|seconds?|secs?|s|yesterday|tomorrow|now|today)
(\s*(?P<separator>and|,)?\s*)?
(\s*(?P<ago>ago)?)?",
@@ -148,6 +149,13 @@ pub fn from_str_at_date(date: NaiveDate, s: &str) -> Result<Duration, ParseDurat
.parse::<i64>()
.map_err(|_| ParseDurationError::InvalidInput)?
};
if let Some(direction) = capture.name("direction") {
if direction.as_str() == "last" {
is_ago = true;
}
}
let unit = capture
.name("unit")
.ok_or(ParseDurationError::InvalidInput)?
@@ -366,4 +374,12 @@ mod tests {
Err(ParseDurationError::InvalidInput)
));
}
#[test]
fn test_direction() {
assert_eq!(from_str("last hour").unwrap(), Duration::seconds(-3600));
assert_eq!(from_str("next year").unwrap(), Duration::days(365));
assert_eq!(from_str("next week").unwrap(), Duration::days(7));
assert_eq!(from_str("last month").unwrap(), Duration::days(-30));
}
}