pub fn from_human_time(
str: &str,
now: NaiveDateTime,
) -> Result<ParseResult, ParseError>Expand description
Parses a human-readable date or time string and converts it into a structured date/time format.
This function takes a string representing a human-readable date/time expression (e.g.,
“Last Friday at 19:45”) and attempts to parse it into one of three possible formats:
NaiveDateTime, NaiveDate, or NaiveTime. The function requires a reference date (now)
to properly resolve relative time expressions.
§Parameters
str: A human-readable date/time string (e.g., “yesterday”, “next Monday at 14:00”).now: The referenceNaiveDateTimerepresenting the current time, used for resolving relative expressions like “yesterday” or “next week”.
§Returns
Ok(ParseResult::DateTime(dt))if the input string represents a full date and time.Ok(ParseResult::Date(d))if the input string represents only a date.Ok(ParseResult::Time(t))if the input string represents only a time.Err(ParseError)if parsing fails due to an unrecognized or invalid format.
§Errors
This function returns an error if the input string contains values that cannot be parsed into a valid date or time.
§Examples
use chrono::Local;
use human_date_parser::{from_human_time, ParseResult};
let now = Local::now().naive_local();
let date = from_human_time("Last Friday at 19:45", now).unwrap();
match date {
ParseResult::DateTime(date) => println!("{date}"),
_ => unreachable!(),
}use chrono::Local;
use human_date_parser::{from_human_time, ParseResult};
let now = Local::now().naive_local();
let date = from_human_time("Next Monday", now).unwrap();
match date {
ParseResult::Date(date) => println!("{date}"),
_ => unreachable!(),
}Examples found in repository?
More examples
examples/stdin.rs (line 15)
6fn main() {
7 let mut buffer = String::new();
8 let stdin = stdin();
9
10 println!("Describe a date or time:");
11 loop {
12 buffer.clear();
13 stdin.read_line(&mut buffer).unwrap();
14 let now = Local::now().naive_local();
15 let result = match human_date_parser::from_human_time(&buffer, now) {
16 Ok(time) => time,
17 Err(e) => {
18 println!("{e}");
19 continue;
20 }
21 };
22
23 let now = Local::now();
24
25 match result {
26 ParseResult::DateTime(datetime) => {
27 println!("Time now: {now}");
28 println!("Time then: {datetime}\n");
29 }
30 ParseResult::Date(date) => println!("Date: {date}\n"),
31 ParseResult::Time(time) => println!("Time: {time}\n"),
32 };
33 }
34}