Function parse_datetime::from_str

source ·
pub fn from_str(s: &str) -> Result<Duration, ParseDurationError>
Expand description

Parses a relative time string and returns a Duration representing the relative time.

Arguments

  • s - A string slice representing the relative time.

Examples

use chrono::Duration;
let duration = parse_datetime::from_str("+3 days");
assert_eq!(duration.unwrap(), Duration::days(3));

Supported formats

The function supports the following formats for relative time:

  • num unit (e.g., “-1 hour”, “+3 days”)
  • unit (e.g., “hour”, “day”)
  • “now” or “today”
  • “yesterday”
  • “tomorrow”
  • use “ago” for the past

[num] can be a positive or negative integer. unit can be one of the following: “fortnight”, “week”, “day”, “hour”, “minute”, “min”, “second”, “sec” and their plural forms.

It is also possible to pass “1 hour 2 minutes” or “2 days and 2 hours”

Returns

  • Ok(Duration) - If the input string can be parsed as a relative time
  • Err(ParseDurationError) - If the input string cannot be parsed as a relative time

Errors

This function will return Err(ParseDurationError::InvalidInput) if the input string cannot be parsed as a relative time.

Examples

use chrono::Duration;
use parse_datetime::{from_str, ParseDurationError};

assert_eq!(from_str("1 hour, 30 minutes").unwrap(), Duration::minutes(90));
assert_eq!(from_str("tomorrow").unwrap(), Duration::days(1));
assert!(matches!(from_str("invalid"), Err(ParseDurationError::InvalidInput)));