Skip to content

Commit c24d593

Browse files
committed
add 'next' and 'last' support
1 parent bed2d16 commit c24d593

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ The `from_str` and `from_str_at_date` functions support the following formats fo
5858
- "yesterday"
5959
- "tomorrow"
6060
- use "ago" for the past
61+
- use "next" or "last" with `unit` (e.g., "next week", "last year")
6162
- combined units with "and" or "," (e.g., "2 years and 1 month", "1 day, 2 hours" or "2 weeks 1 second")
6263

6364
`num` can be a positive or negative integer.

src/lib.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,7 @@ pub fn from_str_at_date(date: NaiveDate, s: &str) -> Result<Duration, ParseDurat
124124
let time_pattern: Regex = Regex::new(
125125
r"(?x)
126126
(?:(?P<value>[-+]?\d*)\s*)?
127+
(\s*(?P<direction>next|last)?\s*)?
127128
(?P<unit>years?|months?|fortnights?|weeks?|days?|hours?|h|minutes?|mins?|m|seconds?|secs?|s|yesterday|tomorrow|now|today)
128129
(\s*(?P<separator>and|,)?\s*)?
129130
(\s*(?P<ago>ago)?)?",
@@ -148,6 +149,13 @@ pub fn from_str_at_date(date: NaiveDate, s: &str) -> Result<Duration, ParseDurat
148149
.parse::<i64>()
149150
.map_err(|_| ParseDurationError::InvalidInput)?
150151
};
152+
153+
if let Some(direction) = capture.name("direction") {
154+
if direction.as_str() == "last" {
155+
is_ago = true;
156+
}
157+
}
158+
151159
let unit = capture
152160
.name("unit")
153161
.ok_or(ParseDurationError::InvalidInput)?
@@ -366,4 +374,12 @@ mod tests {
366374
Err(ParseDurationError::InvalidInput)
367375
));
368376
}
377+
378+
#[test]
379+
fn test_direction() {
380+
assert_eq!(from_str("last hour").unwrap(), Duration::seconds(-3600));
381+
assert_eq!(from_str("next year").unwrap(), Duration::days(365));
382+
assert_eq!(from_str("next week").unwrap(), Duration::days(7));
383+
assert_eq!(from_str("last month").unwrap(), Duration::days(-30));
384+
}
369385
}

0 commit comments

Comments
 (0)