30 Commits

Author SHA1 Message Date
Sylvestre Ledru 02e5c22985 Merge pull request #46 from philolo1/feature/update-version
update version to 0.5.0
2023-09-14 17:51:04 +02:00
Daniel Hofstetter c6feb9a251 Merge pull request #48 from uutils/renovate/codecov-codecov-action-4.x
Update codecov/codecov-action action to v4
2023-09-14 17:44:30 +02:00
renovate[bot] 852638fef0 Update codecov/codecov-action action to v4 2023-09-14 15:32:52 +00:00
Daniel Hofstetter 5c34517469 Merge pull request #47 from uutils/renovate/actions-checkout-4.x
Update actions/checkout action to v4
2023-09-04 17:10:51 +02:00
renovate[bot] 47c5f3620b Update actions/checkout action to v4 2023-09-04 14:54:00 +00:00
Patrick Klitzke 1e43cc945f update parse_datetime to version to 0.5.0
update fuzz to version to 0.2.0
2023-09-04 17:50:42 +09:00
Sylvestre Ledru f9ce5047a5 Merge pull request #45 from cakebaker/use_rust_2021_edition
Use Rust 2021 edition for fuzzing
2023-09-02 18:05:41 +02:00
Daniel Hofstetter 4c3fd2b1ed Merge pull request #44 from uutils/renovate/regex-1.x
Update Rust crate regex to 1.9.5
2023-09-02 17:54:09 +02:00
Daniel Hofstetter 9a7f87ac09 Use Rust 2021 edition for fuzzing 2023-09-02 17:49:26 +02:00
renovate[bot] 0b0aa70193 Update Rust crate regex to 1.9.5 2023-09-02 15:29:56 +00:00
Daniel Hofstetter 0c44becec8 Merge pull request #42 from cakebaker/remove_time_crate
Adapt chrono settings to remove old time crate
2023-08-30 11:38:15 +02:00
Daniel Hofstetter 64dfea4b47 Adapt chrono settings to remove old time crate 2023-08-30 08:12:18 +02:00
Terts Diepraam 0bdabd5303 Merge pull request #41 from philolo1/fix/spelling
Fix small smelling error in readme
2023-08-30 07:46:09 +02:00
Patrick Klitzke 2112830d8b Fix small smelling error in readme 2023-08-30 14:39:34 +09:00
Terts Diepraam 2737b4a0f2 Merge pull request #33 from philolo1/fix/datetime-should-parse-relative
Make parse_datetime::parse_datetime::from_str accept relative time
2023-08-29 10:06:09 +02:00
Patrick Klitzke f10749eade Refactor parse_datetime to only expose parse_datetime function
Create new file parse_relative_time.rs with the relative time helper function.
Renames from_str to parse_datetime and parse_relative time.
Adds function parse_datetime_at_date.
2023-08-29 09:03:17 +09:00
Terts Diepraam a7380508bc Merge pull request #38 from cakebaker/use_timestamp_opt_instead_of_timestamp
Use timestamp_opt() instead of timestamp() in test
2023-08-28 10:06:16 +02:00
Daniel Hofstetter 7f0a909752 Use timestamp_opt() instead of timestamp() in test 2023-08-28 09:34:38 +02:00
Daniel Hofstetter ff0f99bea5 Merge pull request #35 from uutils/renovate/regex-1.x
Update Rust crate regex to 1.9.4
2023-08-27 11:30:45 +02:00
renovate[bot] dc0d8a3aa0 Update Rust crate regex to 1.9.4 2023-08-26 17:26:24 +00:00
Sylvestre Ledru b615effc4e Merge pull request #32 from philolo1/fix/add-unix-timestamp-test
Add tests for unix timestamp
2023-08-22 13:25:05 -04:00
Patrick Klitzke cebf55cf82 Add a unix timestamp
This pr adds tests to support the @ unix timestamp.
2023-08-21 19:40:43 +09:00
Sylvestre Ledru efee20bf01 Merge pull request #29 from uutils/renovate/regex-1.x
Update Rust crate regex to 1.9.3
2023-08-21 07:10:25 +02:00
Sylvestre Ledru c084001056 Merge pull request #31 from Benjscho/main
Add test for parsing epoch seconds
2023-08-21 07:10:15 +02:00
Ben Schofield a35530ed4a Add test for parsing epoch seconds
Add test to verify epoch seconds can be parsed by `parse_datetime`.
2023-08-20 18:41:39 -07:00
renovate[bot] 6cfcc985a8 Update Rust crate regex to 1.9.3 2023-08-06 00:15:26 +00:00
Sylvestre Ledru 497bebb9e7 Merge pull request #27 from uutils/renovate/regex-1.x
Update Rust crate regex to v1.9.1
2023-07-08 14:21:03 +02:00
renovate[bot] dfd43a6d65 Update Rust crate regex to v1.9.1 2023-07-07 20:20:30 +00:00
Sylvestre Ledru 51dd843ded Merge pull request #26 from undali/f19
add 'next' and 'last' support
2023-07-02 22:10:16 +02:00
undali c24d593821 add 'next' and 'last' support 2023-06-26 16:00:57 +04:00
13 changed files with 1022 additions and 786 deletions
+8 -14
View File
@@ -13,7 +13,7 @@ jobs:
matrix:
os: [ubuntu-latest, macOS-latest, windows-latest]
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- uses: actions-rs/toolchain@v1
with:
profile: minimal
@@ -30,7 +30,7 @@ jobs:
matrix:
os: [ubuntu-latest, macOS-latest, windows-latest]
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- uses: actions-rs/toolchain@v1
with:
profile: minimal
@@ -44,7 +44,7 @@ jobs:
name: cargo fmt --all -- --check
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- uses: actions-rs/toolchain@v1
with:
profile: minimal
@@ -63,7 +63,7 @@ jobs:
matrix:
os: [ubuntu-latest, macOS-latest, windows-latest]
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- uses: actions-rs/toolchain@v1
with:
profile: minimal
@@ -86,7 +86,7 @@ jobs:
- { os: macos-latest , features: macos }
- { os: windows-latest , features: windows }
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Initialize workflow variables
id: vars
shell: bash
@@ -155,7 +155,7 @@ jobs:
grcov . --output-type lcov --output-path "${COVERAGE_REPORT_FILE}" --branch --ignore build.rs --ignore "vendor/*" --ignore "/*" --ignore "[a-zA-Z]:/*" --excl-br-line "^\s*((debug_)?assert(_eq|_ne)?!|#\[derive\()"
echo "report=${COVERAGE_REPORT_FILE}" >> $GITHUB_OUTPUT
- name: Upload coverage results (to Codecov.io)
uses: codecov/codecov-action@v3
uses: codecov/codecov-action@v4
# if: steps.vars.outputs.HAS_CODECOV_TOKEN
with:
# token: ${{ secrets.CODECOV_TOKEN }}
@@ -171,7 +171,7 @@ jobs:
env:
RUN_FOR: 60
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@nightly
- name: Install `cargo-fuzz`
run: cargo install cargo-fuzz
@@ -181,10 +181,4 @@ jobs:
run: |
## Run it
cd fuzz
cargo +nightly fuzz run fuzz_from_str -- -max_total_time=${{ env.RUN_FOR }} -detect_leaks=0
- name: Run fuzz_parse_datetime_from_str for XX seconds
shell: bash
run: |
## Run it
cd fuzz
cargo +nightly fuzz run fuzz_parse_datetime_from_str -- -max_total_time=${{ env.RUN_FOR }} -detect_leaks=0
cargo +nightly fuzz run fuzz_parse_datetime -- -max_total_time=${{ env.RUN_FOR }} -detect_leaks=0
Generated
+17 -5
View File
@@ -135,7 +135,7 @@ checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
[[package]]
name = "parse_datetime"
version = "0.4.0"
version = "0.5.0"
dependencies = [
"chrono",
"regex",
@@ -161,9 +161,21 @@ dependencies = [
[[package]]
name = "regex"
version = "1.8.1"
version = "1.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af83e617f331cc6ae2da5443c602dfa5af81e517212d9d611a5b3ba1777b5370"
checksum = "b2eae68fc220f7cf2532e4494aded17545fce192d59cd996e0fe7887f4ceb575"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e9aaecc05d5c4b5f7da074b9a0d1a0867e71fd36e7fc0482d8bcfe8e8fc56290"
dependencies = [
"aho-corasick",
"memchr",
@@ -172,9 +184,9 @@ dependencies = [
[[package]]
name = "regex-syntax"
version = "0.7.1"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5996294f19bd3aae0453a862ad728f60e6600695733dd5df01da90c54363a3c"
checksum = "2ab07dc67230e4a4718e70fd5c20055a4334b121f1f9db8fe63ef39ce9b8c846"
[[package]]
name = "syn"
+3 -3
View File
@@ -1,12 +1,12 @@
[package]
name = "parse_datetime"
description = " parsing human-readable relative time strings and converting them to a Duration"
version = "0.4.0"
description = "parsing human-readable time strings and converting them to a DateTime"
version = "0.5.0"
edition = "2021"
license = "MIT"
repository = "https://github.com/uutils/parse_datetime"
readme = "README.md"
[dependencies]
regex = "1.8"
regex = "1.9"
chrono = { version="0.4", default-features=false, features=["std", "alloc", "clock"] }
+21 -26
View File
@@ -4,7 +4,7 @@
[![License](http://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/uutils/parse_datetime/blob/main/LICENSE)
[![CodeCov](https://codecov.io/gh/uutils/parse_datetime/branch/main/graph/badge.svg)](https://codecov.io/gh/uutils/parse_datetime)
A Rust crate for parsing human-readable relative time strings and converting them to a `Duration`, or parsing human-readable datetime strings and converting them to a `DateTime`.
A Rust crate for parsing human-readable relative time strings and human-readable datetime strings and converting them to a `DateTime`.
## Features
@@ -23,23 +23,23 @@ Add this to your `Cargo.toml`:
parse_datetime = "0.4.0"
```
Then, import the crate and use the `from_str` and `from_str_at_date` functions:
Then, import the crate and use the `parse_datetime_at_date` function:
```rs
use parse_datetime::{from_str, from_str_at_date};
use chrono::Duration;
use chrono::{Duration, Local};
use parse_datetime::parse_datetime_at_date;
let duration = from_str("+3 days");
assert_eq!(duration.unwrap(), Duration::days(3));
let now = Local::now();
let after = parse_datetime_at_date(now, "+3 days");
let today = Utc::today().naive_utc();
let yesterday = today - Duration::days(1);
assert_eq!(
from_str_at_date(yesterday, "2 days").unwrap(),
Duration::days(1)
(now + Duration::days(3)).naive_utc(),
after.unwrap().naive_utc()
);
```
For DateTime parsing, import the `parse_datetime` module:
```rs
use parse_datetime::parse_datetime::from_str;
use chrono::{Local, TimeZone};
@@ -50,7 +50,7 @@ assert_eq!(dt.unwrap(), Local.with_ymd_and_hms(2021, 2, 14, 6, 37, 47).unwrap())
### Supported Formats
The `from_str` and `from_str_at_date` functions support the following formats for relative time:
The `parse_datetime` and `parse_datetime_at_date` functions support absolute datetime and the following relative times:
- `num` `unit` (e.g., "-1 hour", "+3 days")
- `unit` (e.g., "hour", "day")
@@ -58,35 +58,30 @@ 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")
- unix timestamps (for example "@0" "@1344000")
`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.
## Return Values
### Duration
### parse_datetime and parse_datetime_at_date
The `from_str` and `from_str_at_date` functions return:
The `parse_datetime` and `parse_datetime_at_date` function return:
- `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
This function will return `Err(ParseDurationError::InvalidInput)` if the input string
cannot be parsed as a relative time.
### parse_datetime
The `from_str` function returns:
- `Ok(DateTime<FixedOffset>)` - If the input string can be prsed as a datetime
- `Err(ParseDurationError::InvalidInput)` - If the input string cannot be parsed
- `Ok(DateTime<FixedOffset>)` - If the input string can be parsed as a datetime
- `Err(ParseDateTimeError::InvalidInput)` - If the input string cannot be parsed
## Fuzzer
To run the fuzzer:
```
$ cargo fuzz run fuzz_from_str
$ cd fuzz
$ cargo install cargo-fuzz
$ cargo +nightly fuzz run fuzz_parse_datetime
```
## License
+1
View File
@@ -0,0 +1 @@
corpus
+22 -30
View File
@@ -67,10 +67,7 @@ checksum = "ec837a71355b28f6556dbd569b37b3f363091c0bd4b2e735674521b4c5fd9bc5"
dependencies = [
"android-tzdata",
"iana-time-zone",
"js-sys",
"num-traits",
"time",
"wasm-bindgen",
"winapi",
]
@@ -81,8 +78,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa"
[[package]]
name = "fuzz_from_str"
version = "0.1.0"
name = "fuzz_parse_datetime"
version = "0.2.0"
dependencies = [
"chrono",
"libfuzzer-sys",
@@ -99,7 +96,7 @@ checksum = "c85e1d9ab2eadba7e5040d4e09cbd6d072b76a557ad64e797c2cb9d4da21d7e4"
dependencies = [
"cfg-if",
"libc",
"wasi 0.11.0+wasi-snapshot-preview1",
"wasi",
]
[[package]]
@@ -168,9 +165,9 @@ checksum = "518ef76f2f87365916b142844c16d8fefd85039bc5699050210a7778ee1cd1de"
[[package]]
name = "memchr"
version = "2.5.0"
version = "2.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
checksum = "5486aed0026218e61b8a01d5fbd5a0a134649abb71a0e53b7bc088529dced86e"
[[package]]
name = "num-traits"
@@ -189,7 +186,7 @@ checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3"
[[package]]
name = "parse_datetime"
version = "0.4.0"
version = "0.5.0"
dependencies = [
"chrono",
"regex",
@@ -251,9 +248,21 @@ dependencies = [
[[package]]
name = "regex"
version = "1.8.4"
version = "1.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0ab3ca65655bb1e41f2a8c8cd662eb4fb035e67c3f78da1d61dffe89d07300f"
checksum = "697061221ea1b4a94a624f67d0ae2bfe4e22b8a17b6a192afb11046542cc8c47"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2f401f4955220693b56f8ec66ee9c78abffd8d1c4f23dc41a23839eb88f0795"
dependencies = [
"aho-corasick",
"memchr",
@@ -262,9 +271,9 @@ dependencies = [
[[package]]
name = "regex-syntax"
version = "0.7.2"
version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "436b050e76ed2903236f032a59761c1eb99e1b0aead2c257922771dab1fc8c78"
checksum = "dbb5fb1acd8a1a18b3dd5be62d25485eb770e05afb408a9627d14d451bae12da"
[[package]]
name = "syn"
@@ -277,29 +286,12 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "time"
version = "0.1.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b797afad3f312d1c66a56d11d0316f916356d11bd158fbc6ca6389ff6bf805a"
dependencies = [
"libc",
"wasi 0.10.0+wasi-snapshot-preview1",
"winapi",
]
[[package]]
name = "unicode-ident"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b15811caf2415fb889178633e7724bad2509101cde276048e013b9def5e51fa0"
[[package]]
name = "wasi"
version = "0.10.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f"
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
+7 -13
View File
@@ -1,7 +1,7 @@
[package]
name = "fuzz_from_str"
version = "0.1.0"
edition = "2018"
name = "fuzz_parse_datetime"
version = "0.2.0"
edition = "2021"
[package.metadata]
cargo-fuzz = true
@@ -9,20 +9,14 @@ cargo-fuzz = true
[dependencies]
rand = "0.8.5"
libfuzzer-sys = "0.4"
regex = "1.8.4"
chrono = "0.4"
regex = "1.9.5"
chrono = { version="0.4", default-features=false, features=["std", "alloc", "clock"] }
[dependencies.parse_datetime]
path = "../"
[[bin]]
name = "fuzz_from_str"
path = "fuzz_targets/from_str.rs"
test = false
doc = false
[[bin]]
name = "fuzz_parse_datetime_from_str"
path = "fuzz_targets/parse_datetime_from_str.rs"
name = "fuzz_parse_datetime"
path = "fuzz_targets/parse_datetime.rs"
test = false
doc = false
@@ -4,5 +4,5 @@ use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
let s = std::str::from_utf8(data).unwrap_or("");
let _ = parse_datetime::from_str(s);
let _ = parse_datetime::parse_datetime(s);
});
@@ -1,8 +0,0 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
let s = std::str::from_utf8(data).unwrap_or("");
let _ = parse_datetime::parse_datetime::from_str(s);
});
+322 -287
View File
File diff suppressed because it is too large Load Diff
-252
View File
@@ -1,252 +0,0 @@
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
use chrono::{DateTime, FixedOffset, Local, LocalResult, NaiveDateTime, TimeZone};
use crate::ParseDurationError;
/// Formats that parse input can take.
/// Taken from `touch` coreutils
mod format {
pub(crate) const ISO_8601: &str = "%Y-%m-%d";
pub(crate) const ISO_8601_NO_SEP: &str = "%Y%m%d";
pub(crate) const POSIX_LOCALE: &str = "%a %b %e %H:%M:%S %Y";
pub(crate) const YYYYMMDDHHMM_DOT_SS: &str = "%Y%m%d%H%M.%S";
pub(crate) const YYYYMMDDHHMMSS: &str = "%Y-%m-%d %H:%M:%S.%f";
pub(crate) const YYYYMMDDHHMMS: &str = "%Y-%m-%d %H:%M:%S";
pub(crate) const YYYY_MM_DD_HH_MM: &str = "%Y-%m-%d %H:%M";
pub(crate) const YYYYMMDDHHMM: &str = "%Y%m%d%H%M";
pub(crate) const YYYYMMDDHHMM_OFFSET: &str = "%Y%m%d%H%M %z";
pub(crate) const YYYYMMDDHHMM_UTC_OFFSET: &str = "%Y%m%d%H%MUTC%z";
pub(crate) const YYYYMMDDHHMM_ZULU_OFFSET: &str = "%Y%m%d%H%MZ%z";
pub(crate) const YYYYMMDDHHMM_HYPHENATED_OFFSET: &str = "%Y-%m-%d %H:%M %z";
pub(crate) const YYYYMMDDHHMMS_T_SEP: &str = "%Y-%m-%dT%H:%M:%S";
pub(crate) const UTC_OFFSET: &str = "UTC%#z";
pub(crate) const ZULU_OFFSET: &str = "Z%#z";
}
/// Loosely parses a time string and returns a `DateTime` representing the
/// absolute time of the string.
///
/// # Arguments
///
/// * `s` - A string slice representing the time.
///
/// # Examples
///
/// ```
/// use chrono::{DateTime, Utc, TimeZone};
/// let time = parse_datetime::parse_datetime::from_str("2023-06-03 12:00:01Z");
/// assert_eq!(time.unwrap(), Utc.with_ymd_and_hms(2023, 06, 03, 12, 00, 01).unwrap());
/// ```
///
/// # Supported formats
///
/// The function supports the following formats for time:
///
/// * ISO formats
/// * timezone offsets, e.g., "UTC-0100"
///
/// # Returns
///
/// * `Ok(DateTime<FixedOffset>)` - If the input string can be parsed as a 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.
///
pub fn from_str<S: AsRef<str> + Clone>(s: S) -> Result<DateTime<FixedOffset>, ParseDurationError> {
// TODO: Replace with a proper customiseable parsing solution using `nom`, `grmtools`, or
// similar
// Formats with offsets don't require NaiveDateTime workaround
for fmt in [
format::YYYYMMDDHHMM_OFFSET,
format::YYYYMMDDHHMM_HYPHENATED_OFFSET,
format::YYYYMMDDHHMM_UTC_OFFSET,
format::YYYYMMDDHHMM_ZULU_OFFSET,
] {
if let Ok(parsed) = DateTime::parse_from_str(s.as_ref(), fmt) {
return Ok(parsed);
}
}
// Parse formats with no offset, assume local time
for fmt in [
format::YYYYMMDDHHMMS_T_SEP,
format::YYYYMMDDHHMM,
format::YYYYMMDDHHMMS,
format::YYYYMMDDHHMMSS,
format::YYYY_MM_DD_HH_MM,
format::YYYYMMDDHHMM_DOT_SS,
format::POSIX_LOCALE,
] {
if let Ok(parsed) = NaiveDateTime::parse_from_str(s.as_ref(), fmt) {
if let Ok(dt) = naive_dt_to_fixed_offset(parsed) {
return Ok(dt);
}
}
}
// Parse epoch seconds
if s.as_ref().bytes().next() == Some(b'@') {
if let Ok(parsed) = NaiveDateTime::parse_from_str(&s.as_ref()[1..], "%s") {
if let Ok(dt) = naive_dt_to_fixed_offset(parsed) {
return Ok(dt);
}
}
}
let ts = s.as_ref().to_owned() + "0000";
// Parse date only formats - assume midnight local timezone
for fmt in [format::ISO_8601, format::ISO_8601_NO_SEP] {
let f = fmt.to_owned() + "%H%M";
if let Ok(parsed) = NaiveDateTime::parse_from_str(&ts, &f) {
if let Ok(dt) = naive_dt_to_fixed_offset(parsed) {
return Ok(dt);
}
}
}
// Parse offsets. chrono doesn't provide any functionality to parse
// offsets, so instead we replicate parse_date behaviour by getting
// the current date with local, and create a date time string at midnight,
// before trying offset suffixes
let local = Local::now();
let ts = format!("{}", local.format("%Y%m%d")) + "0000" + s.as_ref();
for fmt in [format::UTC_OFFSET, format::ZULU_OFFSET] {
let f = format::YYYYMMDDHHMM.to_owned() + fmt;
if let Ok(parsed) = DateTime::parse_from_str(&ts, &f) {
return Ok(parsed);
}
}
// Default parse and failure
s.as_ref()
.parse()
.map_err(|_| (ParseDurationError::InvalidInput))
}
// Convert NaiveDateTime to DateTime<FixedOffset> by assuming the offset
// is local time
fn naive_dt_to_fixed_offset(dt: NaiveDateTime) -> Result<DateTime<FixedOffset>, ()> {
let now = Local::now();
match now.offset().from_local_datetime(&dt) {
LocalResult::Single(dt) => Ok(dt),
_ => Err(()),
}
}
#[cfg(test)]
mod tests {
static TEST_TIME: i64 = 1613371067;
#[cfg(test)]
mod iso_8601 {
use std::env;
use crate::{
parse_datetime::from_str, parse_datetime::tests::TEST_TIME, ParseDurationError,
};
#[test]
fn test_t_sep() {
env::set_var("TZ", "UTC");
let dt = "2021-02-15T06:37:47";
let actual = from_str(dt);
assert_eq!(actual.unwrap().timestamp(), TEST_TIME);
}
#[test]
fn test_space_sep() {
env::set_var("TZ", "UTC");
let dt = "2021-02-15 06:37:47";
let actual = from_str(dt);
assert_eq!(actual.unwrap().timestamp(), TEST_TIME);
}
#[test]
fn test_space_sep_offset() {
env::set_var("TZ", "UTC");
let dt = "2021-02-14 22:37:47 -0800";
let actual = from_str(dt);
assert_eq!(actual.unwrap().timestamp(), TEST_TIME);
}
#[test]
fn test_t_sep_offset() {
env::set_var("TZ", "UTC");
let dt = "2021-02-14T22:37:47 -0800";
let actual = from_str(dt);
assert_eq!(actual.unwrap().timestamp(), TEST_TIME);
}
#[test]
fn invalid_formats() {
let invalid_dts = vec!["NotADate", "202104", "202104-12T22:37:47"];
for dt in invalid_dts {
assert_eq!(from_str(dt), Err(ParseDurationError::InvalidInput));
}
}
}
#[cfg(test)]
mod offsets {
use chrono::Local;
use crate::{parse_datetime::from_str, ParseDurationError};
#[test]
fn test_positive_offsets() {
let offsets = vec![
"UTC+07:00",
"UTC+0700",
"UTC+07",
"Z+07:00",
"Z+0700",
"Z+07",
];
let expected = format!("{}{}", Local::now().format("%Y%m%d"), "0000+0700");
for offset in offsets {
let actual = from_str(offset).unwrap();
assert_eq!(expected, format!("{}", actual.format("%Y%m%d%H%M%z")));
}
}
#[test]
fn test_partial_offset() {
let offsets = vec!["UTC+00:15", "UTC+0015", "Z+00:15", "Z+0015"];
let expected = format!("{}{}", Local::now().format("%Y%m%d"), "0000+0015");
for offset in offsets {
let actual = from_str(offset).unwrap();
assert_eq!(expected, format!("{}", actual.format("%Y%m%d%H%M%z")));
}
}
#[test]
fn invalid_offset_format() {
let invalid_offsets = vec!["+0700", "UTC+2", "Z-1", "UTC+01005"];
for offset in invalid_offsets {
assert_eq!(from_str(offset), Err(ParseDurationError::InvalidInput));
}
}
}
/// Used to test example code presented in the README.
mod readme_test {
use crate::parse_datetime::from_str;
use chrono::{Local, TimeZone};
#[test]
fn test_readme_code() {
let dt = from_str("2021-02-14 06:37:47");
assert_eq!(
dt.unwrap(),
Local.with_ymd_and_hms(2021, 2, 14, 6, 37, 47).unwrap()
);
}
}
}
File diff suppressed because it is too large Load Diff
-147
View File
@@ -1,148 +1 @@
use chrono::{Duration, Utc};
use parse_datetime::{from_str, from_str_at_date, ParseDurationError};
#[test]
fn test_invalid_input() {
let result = from_str("foobar");
println!("{result:?}");
assert_eq!(result, Err(ParseDurationError::InvalidInput));
let result = from_str("invalid 1");
assert_eq!(result, Err(ParseDurationError::InvalidInput));
}
#[test]
fn test_duration_parsing() {
assert_eq!(from_str("1 year").unwrap(), Duration::seconds(31_536_000));
assert_eq!(
from_str("-2 years").unwrap(),
Duration::seconds(-63_072_000)
);
assert_eq!(
from_str("2 years ago").unwrap(),
Duration::seconds(-63_072_000)
);
assert_eq!(from_str("year").unwrap(), Duration::seconds(31_536_000));
assert_eq!(from_str("1 month").unwrap(), Duration::seconds(2_592_000));
assert_eq!(
from_str("1 month and 2 weeks").unwrap(),
Duration::seconds(3_801_600)
);
assert_eq!(
from_str("1 month, 2 weeks").unwrap(),
Duration::seconds(3_801_600)
);
assert_eq!(
from_str("1 months 2 weeks").unwrap(),
Duration::seconds(3_801_600)
);
assert_eq!(
from_str("1 month and 2 weeks ago").unwrap(),
Duration::seconds(-3_801_600)
);
assert_eq!(from_str("2 months").unwrap(), Duration::seconds(5_184_000));
assert_eq!(from_str("month").unwrap(), Duration::seconds(2_592_000));
assert_eq!(
from_str("1 fortnight").unwrap(),
Duration::seconds(1_209_600)
);
assert_eq!(
from_str("3 fortnights").unwrap(),
Duration::seconds(3_628_800)
);
assert_eq!(from_str("fortnight").unwrap(), Duration::seconds(1_209_600));
assert_eq!(from_str("1 week").unwrap(), Duration::seconds(604_800));
assert_eq!(
from_str("1 week 3 days").unwrap(),
Duration::seconds(864_000)
);
assert_eq!(
from_str("1 week 3 days ago").unwrap(),
Duration::seconds(-864_000)
);
assert_eq!(from_str("-2 weeks").unwrap(), Duration::seconds(-1_209_600));
assert_eq!(
from_str("2 weeks ago").unwrap(),
Duration::seconds(-1_209_600)
);
assert_eq!(from_str("week").unwrap(), Duration::seconds(604_800));
assert_eq!(from_str("1 day").unwrap(), Duration::seconds(86_400));
assert_eq!(from_str("2 days ago").unwrap(), Duration::seconds(-172_800));
assert_eq!(from_str("-2 days").unwrap(), Duration::seconds(-172_800));
assert_eq!(from_str("day").unwrap(), Duration::seconds(86_400));
assert_eq!(from_str("1 hour").unwrap(), Duration::seconds(3_600));
assert_eq!(from_str("1 h").unwrap(), Duration::seconds(3_600));
assert_eq!(from_str("1 hour ago").unwrap(), Duration::seconds(-3_600));
assert_eq!(from_str("-2 hours").unwrap(), Duration::seconds(-7_200));
assert_eq!(from_str("hour").unwrap(), Duration::seconds(3_600));
assert_eq!(from_str("1 minute").unwrap(), Duration::seconds(60));
assert_eq!(from_str("1 min").unwrap(), Duration::seconds(60));
assert_eq!(from_str("2 minutes").unwrap(), Duration::seconds(120));
assert_eq!(from_str("2 mins").unwrap(), Duration::seconds(120));
assert_eq!(from_str("2m").unwrap(), Duration::seconds(120));
assert_eq!(from_str("min").unwrap(), Duration::seconds(60));
assert_eq!(from_str("1 second").unwrap(), Duration::seconds(1));
assert_eq!(from_str("1 s").unwrap(), Duration::seconds(1));
assert_eq!(from_str("2 seconds").unwrap(), Duration::seconds(2));
assert_eq!(from_str("2 secs").unwrap(), Duration::seconds(2));
assert_eq!(from_str("2 sec").unwrap(), Duration::seconds(2));
assert_eq!(from_str("sec").unwrap(), Duration::seconds(1));
assert_eq!(from_str("now").unwrap(), Duration::seconds(0));
assert_eq!(from_str("today").unwrap(), Duration::seconds(0));
assert_eq!(
from_str("1 year 2 months 4 weeks 3 days and 2 seconds").unwrap(),
Duration::seconds(39_398_402)
);
assert_eq!(
from_str("1 year 2 months 4 weeks 3 days and 2 seconds ago").unwrap(),
Duration::seconds(-39_398_402)
);
}
#[test]
#[should_panic]
fn test_display_parse_duration_error_through_from_str() {
let invalid_input = "9223372036854775807 seconds and 1 second";
let _ = from_str(invalid_input).unwrap();
}
#[test]
fn test_display_should_fail() {
let invalid_input = "Thu Jan 01 12:34:00 2015";
let error = from_str(invalid_input).unwrap_err();
assert_eq!(
format!("{error}"),
"Invalid input string: cannot be parsed as a relative time"
);
}
#[test]
fn test_from_str_at_date_day() {
let today = Utc::now().date_naive();
let yesterday = today - Duration::days(1);
assert_eq!(
from_str_at_date(yesterday, "2 days").unwrap(),
Duration::days(1)
);
}
#[test]
fn test_invalid_input_at_date() {
let today = Utc::now().date_naive();
let result = from_str_at_date(today, "foobar");
println!("{result:?}");
assert_eq!(result, Err(ParseDurationError::InvalidInput));
let result = from_str_at_date(today, "invalid 1r");
assert_eq!(result, Err(ParseDurationError::InvalidInput));
}