Skip to content

Commit

Permalink
Trim whitespace for 'parse_date' input
Browse files Browse the repository at this point in the history
  • Loading branch information
fsktom committed Sep 16, 2023
1 parent 6b33a9e commit c06fb5a
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ use chrono::{DateTime, Local, NaiveDateTime, TimeZone};
/// - 'now'/'end' return the current time
/// - 'start' returns the start of UNIX epoch
///
/// whitespace is trimmed
///
/// # Examples
/// ```
/// use endsong::prelude::*;
Expand All @@ -73,6 +75,9 @@ use chrono::{DateTime, Local, NaiveDateTime, TimeZone};
/// );
///
/// let now: DateTime<Local> = parse_date("now")?;
///
/// // whitespace is trimmed!
/// assert_eq!(parse_date("2019-01-01"), parse_date(" 2019-01-01 "));
/// # Ok::<(), chrono::format::ParseError>(())
/// ```
/// # Errors
Expand All @@ -81,6 +86,7 @@ use chrono::{DateTime, Local, NaiveDateTime, TimeZone};
/// if the `date` does not follow the format `YYYY-MM-DD`
/// and is not 'now'/'end'/'start'
pub fn parse_date(date: &str) -> Result<DateTime<Local>, chrono::format::ParseError> {
let date = date.trim();
match date {
"now" | "end" => Ok(Local::now()),
"start" => {
Expand Down Expand Up @@ -138,10 +144,10 @@ mod tests {
assert!(parse_date("2011-13-12").is_err());
assert!(parse_date("2023-02-29").is_err());

// for some reason, the chrono parser accepts leading whitespace
// but not trailing whitespace...
// whitespace around the input is trimmed
assert!(parse_date(" 2011-01-01").is_ok());
assert!(parse_date("2011-01-01 ").is_err());
assert!(parse_date(" 2011-01-01 ").is_err());
assert!(parse_date("2011-01-01 ").is_ok());
assert!(parse_date(" 2011-01-01 ").is_ok());
assert_eq!(parse_date("2011-01-01"), parse_date(" 2011-01-01 "));
}
}

0 comments on commit c06fb5a

Please sign in to comment.