| 1 |
// For the full copyright and license information, please view the LICENSE |
| 2 |
// file that was distributed with this source code. |
| 3 |
//! A Rust crate for parsing human-readable relative time strings and |
| 4 |
//! human-readable datetime strings. |
| 5 |
//! The function supports the following formats for time: |
| 6 |
//! |
| 7 |
//! * ISO formats |
| 8 |
//! * timezone offsets, e.g., "UTC-0100" |
| 9 |
//! * unix timestamps, e.g., "@12" |
| 10 |
//! * relative time to now, e.g. "+1 hour" |
| 11 |
//! |
| 12 |
use std::error::Error; |
| 13 |
use std::fmt::{self, Display}; |
| 14 |
|
| 15 |
use jiff::Zoned; |
| 16 |
|
| 17 |
mod extended; |
| 18 |
mod items; |
| 19 |
|
| 20 |
pub use extended::{DateParts, ExtendedDateTime, TimeParts}; |
| 21 |
|
| 22 |
/// Maximum year accepted by GNU `date`. |
| 23 |
pub const GNU_MAX_YEAR: u32 = 2_147_485_547; |
| 24 |
|
| 25 |
/// Parsed datetime output. |
| 26 |
/// |
| 27 |
/// - [`ParsedDateTime::InRange`] contains a standard [`jiff::Zoned`] value. |
| 28 |
/// - [`ParsedDateTime::Extended`] contains an out-of-range year representation |
| 29 |
/// (for example, years greater than `9999`) that cannot be represented by |
| 30 |
/// `jiff::Zoned`. |
| 31 |
#[derive(Debug, Clone, PartialEq, Eq)] |
| 32 |
pub enum ParsedDateTime { |
| 33 |
InRange(Zoned), |
| 34 |
Extended(ExtendedDateTime), |
| 35 |
} |
| 36 |
|
| 37 |
impl ParsedDateTime { |
| 38 |
pub fn as_zoned(&self) -> Option<&Zoned> { |
| 39 |
match self { |
| 40 |
ParsedDateTime::InRange(z) => Some(z), |
| 41 |
ParsedDateTime::Extended(_) => None, |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
pub fn into_zoned(self) -> Option<Zoned> { |
| 46 |
match self { |
| 47 |
ParsedDateTime::InRange(z) => Some(z), |
| 48 |
ParsedDateTime::Extended(_) => None, |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
/// Returns the number of seconds since the Unix epoch, using floor |
| 53 |
/// division (rounding toward negative infinity). |
| 54 |
/// |
| 55 |
/// This matches the behavior of GNU `date +%s` for negative fractional |
| 56 |
/// timestamps. For example, a timestamp of −1.5 seconds returns −2 |
| 57 |
/// (not −1 as truncation toward zero would give). |
| 58 |
/// |
| 59 |
/// Note: `jiff::Timestamp::as_second()` uses truncation toward zero, |
| 60 |
/// which differs from the POSIX/GNU convention for `%s`. This method |
| 61 |
/// corrects for that. |
| 62 |
pub fn unix_epoch_second(&self) -> i64 { |
| 63 |
match self { |
| 64 |
ParsedDateTime::InRange(z) => { |
| 65 |
let ts = z.timestamp(); |
| 66 |
let s = ts.as_second(); |
| 67 |
let ns = ts.subsec_nanosecond(); |
| 68 |
// jiff stores negative fractional timestamps with a negative |
| 69 |
// subsec_nanosecond (e.g. -1.5s → as_second=-1, subsec=-500ms). |
| 70 |
// Floor semantics require subtracting 1 from the second when |
| 71 |
// the nanosecond component is negative. |
| 72 |
if ns < 0 { |
| 73 |
s - 1 |
| 74 |
} else { |
| 75 |
s |
| 76 |
} |
| 77 |
} |
| 78 |
ParsedDateTime::Extended(ext) => ext.unix_seconds(), |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
/// Returns the sub-second nanosecond component, always in `0..1_000_000_000`. |
| 83 |
/// |
| 84 |
/// This is the complement of [`unix_epoch_second`](Self::unix_epoch_second): |
| 85 |
/// the full timestamp equals `unix_epoch_second() + subsec_nanosecond() / 1e9`. |
| 86 |
/// |
| 87 |
/// For negative fractional timestamps the nanosecond is re-normalized to be |
| 88 |
/// non-negative (matching the GNU `timespec` convention). |
| 89 |
pub fn subsec_nanosecond(&self) -> i32 { |
| 90 |
match self { |
| 91 |
ParsedDateTime::InRange(z) => { |
| 92 |
let ns = z.timestamp().subsec_nanosecond(); |
| 93 |
if ns < 0 { |
| 94 |
1_000_000_000 + ns |
| 95 |
} else { |
| 96 |
ns |
| 97 |
} |
| 98 |
} |
| 99 |
ParsedDateTime::Extended(_) => 0, |
| 100 |
} |
| 101 |
} |
| 102 |
|
| 103 |
/// Unwraps the `InRange` variant, panicking if this is an `Extended` value. |
| 104 |
/// |
| 105 |
/// This is a convenience for contexts where the caller is certain the result |
| 106 |
/// is in range (e.g., tests). Prefer [`into_zoned`](Self::into_zoned) or |
| 107 |
/// pattern matching in production code. |
| 108 |
pub fn expect_in_range(self) -> Zoned { |
| 109 |
self.into_zoned() |
| 110 |
.expect("ParsedDateTime is not representable as jiff::Zoned") |
| 111 |
} |
| 112 |
} |
| 113 |
|
| 114 |
impl fmt::Display for ParsedDateTime { |
| 115 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 116 |
match self { |
| 117 |
ParsedDateTime::InRange(z) => { |
| 118 |
let ns = z.datetime().time().subsec_nanosecond(); |
| 119 |
if ns != 0 { |
| 120 |
write!(f, "{}", z.strftime("%Y-%m-%d %H:%M:%S%.9f%:z")) |
| 121 |
} else { |
| 122 |
write!(f, "{}", z.strftime("%Y-%m-%d %H:%M:%S%:z")) |
| 123 |
} |
| 124 |
} |
| 125 |
ParsedDateTime::Extended(dt) => write!(f, "{dt}"), |
| 126 |
} |
| 127 |
} |
| 128 |
} |
| 129 |
|
| 130 |
/// An `Extended` value never compares equal to a `Zoned`. |
| 131 |
impl PartialEq<Zoned> for ParsedDateTime { |
| 132 |
fn eq(&self, other: &Zoned) -> bool { |
| 133 |
match self { |
| 134 |
ParsedDateTime::InRange(z) => z == other, |
| 135 |
ParsedDateTime::Extended(_) => false, |
| 136 |
} |
| 137 |
} |
| 138 |
} |
| 139 |
|
| 140 |
#[derive(Debug, PartialEq)] |
| 141 |
pub enum ParseDateTimeError { |
| 142 |
InvalidInput, |
| 143 |
} |
| 144 |
|
| 145 |
impl Display for ParseDateTimeError { |
| 146 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 147 |
match self { |
| 148 |
ParseDateTimeError::InvalidInput => write!(f, "Invalid input string"), |
| 149 |
} |
| 150 |
} |
| 151 |
} |
| 152 |
|
| 153 |
impl Error for ParseDateTimeError {} |
| 154 |
|
| 155 |
impl From<items::error::Error> for ParseDateTimeError { |
| 156 |
fn from(_: items::error::Error) -> Self { |
| 157 |
ParseDateTimeError::InvalidInput |
| 158 |
} |
| 159 |
} |
| 160 |
|
| 161 |
/// Parses a time string and returns a [`ParsedDateTime`] representing the |
| 162 |
/// absolute time of the string. |
| 163 |
/// |
| 164 |
/// # Arguments |
| 165 |
/// |
| 166 |
/// * `input` - A string slice representing the time. |
| 167 |
/// |
| 168 |
/// # Examples |
| 169 |
/// |
| 170 |
/// ``` |
| 171 |
/// use parse_datetime::{parse_datetime, ParsedDateTime}; |
| 172 |
/// |
| 173 |
/// let time = parse_datetime("2023-06-03 12:00:01Z").unwrap(); |
| 174 |
/// match time { |
| 175 |
/// ParsedDateTime::InRange(z) => { |
| 176 |
/// assert_eq!(z.strftime("%F %T").to_string(), "2023-06-03 12:00:01"); |
| 177 |
/// } |
| 178 |
/// ParsedDateTime::Extended(_) => unreachable!("unexpected for this input"), |
| 179 |
/// } |
| 180 |
/// ``` |
| 181 |
/// |
| 182 |
/// |
| 183 |
/// # Returns |
| 184 |
/// |
| 185 |
/// * `Ok(ParsedDateTime)` - If the input string can be parsed as a time |
| 186 |
/// * `Err(ParseDateTimeError)` - If the input string cannot be parsed |
| 187 |
/// |
| 188 |
/// # Errors |
| 189 |
/// |
| 190 |
/// This function will return `Err(ParseDateTimeError::InvalidInput)` if the |
| 191 |
/// input string cannot be parsed. |
| 192 |
pub fn parse_datetime<S: AsRef<str> + Clone>( |
| 193 |
input: S, |
| 194 |
) -> Result<ParsedDateTime, ParseDateTimeError> { |
| 195 |
items::parse_at_local(input).map_err(|e| e.into()) |
| 196 |
} |
| 197 |
|
| 198 |
/// Parses a time string at a specific date and returns a [`ParsedDateTime`] |
| 199 |
/// representing the absolute time of the string. |
| 200 |
/// |
| 201 |
/// # Arguments |
| 202 |
/// |
| 203 |
/// * date - The date represented in local time |
| 204 |
/// * `input` - A string slice representing the time. |
| 205 |
/// |
| 206 |
/// # Examples |
| 207 |
/// |
| 208 |
/// ``` |
| 209 |
/// use jiff::Zoned; |
| 210 |
/// use parse_datetime::{parse_datetime_at_date, ParsedDateTime}; |
| 211 |
/// |
| 212 |
/// let now = Zoned::now(); |
| 213 |
/// let after = parse_datetime_at_date(now, "2024-09-13UTC +3 days").unwrap(); |
| 214 |
/// |
| 215 |
/// match after { |
| 216 |
/// ParsedDateTime::InRange(z) => assert_eq!("2024-09-16", z.strftime("%F").to_string()), |
| 217 |
/// ParsedDateTime::Extended(_) => unreachable!("unexpected for this input"), |
| 218 |
/// } |
| 219 |
/// ``` |
| 220 |
/// |
| 221 |
/// # Returns |
| 222 |
/// |
| 223 |
/// * `Ok(ParsedDateTime)` - If the input string can be parsed as a time |
| 224 |
/// * `Err(ParseDateTimeError)` - If the input string cannot be parsed |
| 225 |
/// |
| 226 |
/// # Errors |
| 227 |
/// |
| 228 |
/// This function will return `Err(ParseDateTimeError::InvalidInput)` if the |
| 229 |
/// input string cannot be parsed. |
| 230 |
pub fn parse_datetime_at_date<S: AsRef<str> + Clone>( |
| 231 |
date: Zoned, |
| 232 |
input: S, |
| 233 |
) -> Result<ParsedDateTime, ParseDateTimeError> { |
| 234 |
items::parse_at_date(date, input).map_err(|e| e.into()) |
| 235 |
} |
| 236 |
|
| 237 |
#[cfg(test)] |
| 238 |
mod tests { |
| 239 |
use jiff::{ |
| 240 |
civil::{date, time, Time, Weekday}, |
| 241 |
ToSpan, Zoned, |
| 242 |
}; |
| 243 |
|
| 244 |
use crate::parse_datetime; |
| 245 |
|
| 246 |
#[cfg(test)] |
| 247 |
mod iso_8601 { |
| 248 |
use crate::parse_datetime; |
| 249 |
|
| 250 |
static TEST_TIME: i64 = 1613371067; |
| 251 |
|
| 252 |
#[test] |
| 253 |
fn test_t_sep() { |
| 254 |
let dt = "2021-02-15T06:37:47 +0000"; |
| 255 |
let actual = parse_datetime(dt).unwrap().expect_in_range(); |
| 256 |
assert_eq!(actual.timestamp().as_second(), TEST_TIME); |
| 257 |
} |
| 258 |
|
| 259 |
#[test] |
| 260 |
fn test_space_sep() { |
| 261 |
let dt = "2021-02-15 06:37:47 +0000"; |
| 262 |
let actual = parse_datetime(dt).unwrap().expect_in_range(); |
| 263 |
assert_eq!(actual.timestamp().as_second(), TEST_TIME); |
| 264 |
} |
| 265 |
|
| 266 |
#[test] |
| 267 |
fn test_space_sep_offset() { |
| 268 |
let dt = "2021-02-14 22:37:47 -0800"; |
| 269 |
let actual = parse_datetime(dt).unwrap().expect_in_range(); |
| 270 |
assert_eq!(actual.timestamp().as_second(), TEST_TIME); |
| 271 |
} |
| 272 |
|
| 273 |
#[test] |
| 274 |
fn test_t_sep_offset() { |
| 275 |
let dt = "2021-02-14T22:37:47 -0800"; |
| 276 |
let actual = parse_datetime(dt).unwrap().expect_in_range(); |
| 277 |
assert_eq!(actual.timestamp().as_second(), TEST_TIME); |
| 278 |
} |
| 279 |
|
| 280 |
#[test] |
| 281 |
fn test_t_sep_single_digit_offset_no_space() { |
| 282 |
let dt = "2021-02-14T22:37:47-8"; |
| 283 |
let actual = parse_datetime(dt).unwrap().expect_in_range(); |
| 284 |
assert_eq!(actual.timestamp().as_second(), TEST_TIME); |
| 285 |
} |
| 286 |
|
| 287 |
#[test] |
| 288 |
fn invalid_formats() { |
| 289 |
let invalid_dts = vec![ |
| 290 |
"NotADate", |
| 291 |
"202104", |
| 292 |
"202104-12T22:37:47", |
| 293 |
"a774e26sec", // 774e26 is not a valid seconds value (we don't accept E-notation) |
| 294 |
"12.", // Invalid floating point number |
| 295 |
]; |
| 296 |
for dt in invalid_dts { |
| 297 |
assert!( |
| 298 |
parse_datetime(dt).is_err(), |
| 299 |
"Expected error for input: {}", |
| 300 |
dt |
| 301 |
); |
| 302 |
} |
| 303 |
} |
| 304 |
|
| 305 |
#[test] |
| 306 |
fn test_epoch_seconds() { |
| 307 |
let dt = "@1613371067"; |
| 308 |
let actual = parse_datetime(dt).unwrap().expect_in_range(); |
| 309 |
assert_eq!(actual.timestamp().as_second(), TEST_TIME); |
| 310 |
} |
| 311 |
|
| 312 |
// #[test] |
| 313 |
// fn test_epoch_seconds_non_utc() { |
| 314 |
// env::set_var("TZ", "EST"); |
| 315 |
// let dt = "@1613371067"; |
| 316 |
// let actual = parse_datetime(dt).unwrap(); |
| 317 |
// assert_eq!(actual.timestamp().as_second(), TEST_TIME); |
| 318 |
// } |
| 319 |
} |
| 320 |
|
| 321 |
#[cfg(test)] |
| 322 |
mod calendar_date_items { |
| 323 |
use jiff::{ |
| 324 |
civil::{date, time}, |
| 325 |
Zoned, |
| 326 |
}; |
| 327 |
|
| 328 |
use crate::parse_datetime; |
| 329 |
|
| 330 |
#[test] |
| 331 |
fn single_digit_month_day() { |
| 332 |
let expected = Zoned::now() |
| 333 |
.with() |
| 334 |
.date(date(1987, 5, 7)) |
| 335 |
.time(time(0, 0, 0, 0)) |
| 336 |
.build() |
| 337 |
.unwrap(); |
| 338 |
|
| 339 |
assert_eq!(parse_datetime("1987-05-07").unwrap(), expected); |
| 340 |
assert_eq!(parse_datetime("1987-5-07").unwrap(), expected); |
| 341 |
assert_eq!(parse_datetime("1987-05-7").unwrap(), expected); |
| 342 |
assert_eq!(parse_datetime("1987-5-7").unwrap(), expected); |
| 343 |
assert_eq!(parse_datetime("5/7/1987").unwrap(), expected); |
| 344 |
assert_eq!(parse_datetime("5/07/1987").unwrap(), expected); |
| 345 |
assert_eq!(parse_datetime("05/7/1987").unwrap(), expected); |
| 346 |
assert_eq!(parse_datetime("05/07/1987").unwrap(), expected); |
| 347 |
} |
| 348 |
} |
| 349 |
|
| 350 |
#[cfg(test)] |
| 351 |
mod offsets { |
| 352 |
use jiff::{civil::DateTime, tz, Zoned}; |
| 353 |
|
| 354 |
use crate::parse_datetime; |
| 355 |
|
| 356 |
#[test] |
| 357 |
fn test_positive_offsets() { |
| 358 |
let offsets = vec![ |
| 359 |
"UTC+07:00", |
| 360 |
"UTC+0700", |
| 361 |
"UTC+07", |
| 362 |
"Z+07:00", |
| 363 |
"Z+0700", |
| 364 |
"Z+07", |
| 365 |
]; |
| 366 |
|
| 367 |
let expected = format!("{}{}", Zoned::now().strftime("%Y%m%d"), "0000+0700"); |
| 368 |
for offset in offsets { |
| 369 |
let actual = parse_datetime(offset).unwrap().expect_in_range(); |
| 370 |
assert_eq!(expected, actual.strftime("%Y%m%d%H%M%z").to_string()); |
| 371 |
} |
| 372 |
} |
| 373 |
|
| 374 |
#[test] |
| 375 |
fn test_partial_offset() { |
| 376 |
let offsets = vec!["UTC+00:15", "UTC+0015", "Z+00:15", "Z+0015"]; |
| 377 |
let expected = format!("{}{}", Zoned::now().strftime("%Y%m%d"), "0000+0015"); |
| 378 |
for offset in offsets { |
| 379 |
let actual = parse_datetime(offset).unwrap().expect_in_range(); |
| 380 |
assert_eq!(expected, actual.strftime("%Y%m%d%H%M%z").to_string()); |
| 381 |
} |
| 382 |
} |
| 383 |
|
| 384 |
#[test] |
| 385 |
fn test_datetime_with_offset() { |
| 386 |
let actual = parse_datetime("1997-01-19 08:17:48 +2").unwrap(); |
| 387 |
let expected = "1997-01-19 08:17:48" |
| 388 |
.parse::<DateTime>() |
| 389 |
.unwrap() |
| 390 |
.to_zoned(tz::TimeZone::fixed(tz::offset(2))) |
| 391 |
.unwrap(); |
| 392 |
assert_eq!(actual, expected); |
| 393 |
} |
| 394 |
|
| 395 |
#[test] |
| 396 |
fn test_datetime_with_timezone() { |
| 397 |
let actual = parse_datetime("1997-01-19 08:17:48 BRT").unwrap(); |
| 398 |
let expected = "1997-01-19 08:17:48" |
| 399 |
.parse::<DateTime>() |
| 400 |
.unwrap() |
| 401 |
.to_zoned(tz::TimeZone::fixed(tz::offset(-3))) |
| 402 |
.unwrap(); |
| 403 |
assert_eq!(actual, expected); |
| 404 |
} |
| 405 |
|
| 406 |
#[test] |
| 407 |
fn offset_overflow() { |
| 408 |
assert!(parse_datetime("m+25").is_err()); |
| 409 |
assert!(parse_datetime("24:00").is_err()); |
| 410 |
} |
| 411 |
} |
| 412 |
|
| 413 |
#[cfg(test)] |
| 414 |
mod relative_time { |
| 415 |
use crate::parse_datetime; |
| 416 |
|
| 417 |
#[test] |
| 418 |
fn test_positive_offsets() { |
| 419 |
let relative_times = vec![ |
| 420 |
"today", |
| 421 |
"yesterday", |
| 422 |
"1 minute", |
| 423 |
"3 hours", |
| 424 |
"1 year 3 months", |
| 425 |
]; |
| 426 |
|
| 427 |
for relative_time in relative_times { |
| 428 |
assert!(parse_datetime(relative_time).is_ok()); |
| 429 |
} |
| 430 |
} |
| 431 |
|
| 432 |
#[test] |
| 433 |
fn integer_seconds_offset() { |
| 434 |
let dt = "0 + 0 seconds"; |
| 435 |
assert!(parse_datetime(dt).is_ok()); |
| 436 |
} |
| 437 |
|
| 438 |
#[test] |
| 439 |
fn integer_seconds_offset_spaceless() { |
| 440 |
let dt = "0+0 seconds"; |
| 441 |
assert!(parse_datetime(dt).is_ok()); |
| 442 |
} |
| 443 |
|
| 444 |
#[test] |
| 445 |
fn floating_seconds_offset() { |
| 446 |
let dt = "0 + 0.0 seconds"; |
| 447 |
assert!(parse_datetime(dt).is_ok()); |
| 448 |
} |
| 449 |
|
| 450 |
#[test] |
| 451 |
fn floating_seconds_offset_spaceless() { |
| 452 |
let dt = "0+0.0 seconds"; |
| 453 |
assert!(parse_datetime(dt).is_ok()); |
| 454 |
} |
| 455 |
|
| 456 |
#[test] |
| 457 |
fn floating_seconds_offset_from_now() { |
| 458 |
let dt = "now + 1.5 seconds"; |
| 459 |
assert!(parse_datetime(dt).is_ok()); |
| 460 |
} |
| 461 |
|
| 462 |
#[test] |
| 463 |
fn floating_seconds_offset_from_tomorrow_spaceless() { |
| 464 |
let dt = "tomorrow+1.5 seconds"; |
| 465 |
assert!(parse_datetime(dt).is_ok()); |
| 466 |
} |
| 467 |
} |
| 468 |
|
| 469 |
#[cfg(test)] |
| 470 |
mod weekday { |
| 471 |
use jiff::{civil::DateTime, tz::TimeZone, Zoned}; |
| 472 |
|
| 473 |
use crate::parse_datetime_at_date; |
| 474 |
|
| 475 |
fn get_formatted_date(date: &Zoned, weekday: &str) -> String { |
| 476 |
let result = parse_datetime_at_date(date.clone(), weekday) |
| 477 |
.unwrap() |
| 478 |
.expect_in_range(); |
| 479 |
|
| 480 |
result.strftime("%F %T %9f").to_string() |
| 481 |
} |
| 482 |
|
| 483 |
#[test] |
| 484 |
fn test_weekday() { |
| 485 |
// add some constant hours and minutes and seconds to check its reset |
| 486 |
let date = "2023-02-28 10:12:03" |
| 487 |
.parse::<DateTime>() |
| 488 |
.unwrap() |
| 489 |
.to_zoned(TimeZone::system()) |
| 490 |
.unwrap(); |
| 491 |
|
| 492 |
// 2023-2-28 is tuesday |
| 493 |
assert_eq!( |
| 494 |
get_formatted_date(&date, "tuesday"), |
| 495 |
"2023-02-28 00:00:00 000000000" |
| 496 |
); |
| 497 |
|
| 498 |
// 2023-3-01 is wednesday |
| 499 |
assert_eq!( |
| 500 |
get_formatted_date(&date, "wed"), |
| 501 |
"2023-03-01 00:00:00 000000000" |
| 502 |
); |
| 503 |
|
| 504 |
assert_eq!( |
| 505 |
get_formatted_date(&date, "thu"), |
| 506 |
"2023-03-02 00:00:00 000000000" |
| 507 |
); |
| 508 |
|
| 509 |
assert_eq!( |
| 510 |
get_formatted_date(&date, "fri"), |
| 511 |
"2023-03-03 00:00:00 000000000" |
| 512 |
); |
| 513 |
|
| 514 |
assert_eq!( |
| 515 |
get_formatted_date(&date, "sat"), |
| 516 |
"2023-03-04 00:00:00 000000000" |
| 517 |
); |
| 518 |
|
| 519 |
assert_eq!( |
| 520 |
get_formatted_date(&date, "sun"), |
| 521 |
"2023-03-05 00:00:00 000000000" |
| 522 |
); |
| 523 |
} |
| 524 |
} |
| 525 |
|
| 526 |
#[cfg(test)] |
| 527 |
mod timestamp { |
| 528 |
use jiff::Timestamp; |
| 529 |
|
| 530 |
use crate::parse_datetime; |
| 531 |
|
| 532 |
#[test] |
| 533 |
fn test_positive_and_negative_offsets() { |
| 534 |
let offsets: Vec<i64> = vec![ |
| 535 |
0, 1, 2, 10, 100, 150, 2000, 1234400000, 1334400000, 1692582913, 2092582910, |
| 536 |
]; |
| 537 |
|
| 538 |
for offset in offsets { |
| 539 |
// positive offset |
| 540 |
let time = Timestamp::from_second(offset).unwrap(); |
| 541 |
let dt = parse_datetime(format!("@{offset}")) |
| 542 |
.unwrap() |
| 543 |
.expect_in_range(); |
| 544 |
assert_eq!(dt.timestamp(), time); |
| 545 |
|
| 546 |
// negative offset |
| 547 |
let time = Timestamp::from_second(-offset).unwrap(); |
| 548 |
let dt = parse_datetime(format!("@-{offset}")) |
| 549 |
.unwrap() |
| 550 |
.expect_in_range(); |
| 551 |
assert_eq!(dt.timestamp(), time); |
| 552 |
} |
| 553 |
} |
| 554 |
} |
| 555 |
|
| 556 |
/// Used to test example code presented in the README. |
| 557 |
mod readme_test { |
| 558 |
use jiff::{civil::DateTime, tz::TimeZone}; |
| 559 |
|
| 560 |
use crate::parse_datetime; |
| 561 |
|
| 562 |
#[test] |
| 563 |
fn test_readme_code() { |
| 564 |
let dt = parse_datetime("2021-02-14 06:37:47").unwrap(); |
| 565 |
let expected = "2021-02-14 06:37:47" |
| 566 |
.parse::<DateTime>() |
| 567 |
.unwrap() |
| 568 |
.to_zoned(TimeZone::system()) |
| 569 |
.unwrap(); |
| 570 |
|
| 571 |
assert_eq!(dt, expected); |
| 572 |
} |
| 573 |
} |
| 574 |
|
| 575 |
mod invalid_test { |
| 576 |
use crate::parse_datetime; |
| 577 |
use crate::ParseDateTimeError; |
| 578 |
|
| 579 |
#[test] |
| 580 |
fn test_invalid_input() { |
| 581 |
let result = parse_datetime("foobar"); |
| 582 |
assert_eq!(result, Err(ParseDateTimeError::InvalidInput)); |
| 583 |
|
| 584 |
let result = parse_datetime("invalid 1"); |
| 585 |
assert_eq!(result, Err(ParseDateTimeError::InvalidInput)); |
| 586 |
} |
| 587 |
} |
| 588 |
|
| 589 |
#[test] |
| 590 |
fn test_datetime_ending_in_z() { |
| 591 |
let actual = parse_datetime("2023-06-03 12:00:01Z").unwrap(); |
| 592 |
let expected = "2023-06-03 12:00:01[UTC]".parse::<Zoned>().unwrap(); |
| 593 |
assert_eq!(actual, expected); |
| 594 |
} |
| 595 |
|
| 596 |
#[test] |
| 597 |
fn parsed_datetime_accessors_cover_both_variants() { |
| 598 |
let in_range = parse_datetime("2023-06-03 12:00:01Z").unwrap(); |
| 599 |
assert!(in_range.as_zoned().is_some()); |
| 600 |
assert!(in_range.into_zoned().is_some()); |
| 601 |
|
| 602 |
let extended = parse_datetime("10000-01-01").unwrap(); |
| 603 |
assert!(extended.as_zoned().is_none()); |
| 604 |
assert!(extended.into_zoned().is_none()); |
| 605 |
} |
| 606 |
|
| 607 |
#[test] |
| 608 |
fn parsed_datetime_extended_never_equals_zoned() { |
| 609 |
let extended = parse_datetime("10000-01-01").unwrap(); |
| 610 |
let zoned = Zoned::now(); |
| 611 |
assert_ne!(extended, zoned); |
| 612 |
} |
| 613 |
|
| 614 |
#[test] |
| 615 |
fn test_parse_invalid_datetime() { |
| 616 |
assert!(crate::parse_datetime("bogus +1 day").is_err()); |
| 617 |
} |
| 618 |
|
| 619 |
#[test] |
| 620 |
fn test_parse_invalid_delta() { |
| 621 |
assert!(crate::parse_datetime("1997-01-01 bogus").is_err()); |
| 622 |
} |
| 623 |
|
| 624 |
#[test] |
| 625 |
fn test_parse_datetime_tz_nodelta() { |
| 626 |
// 1997-01-01 00:00:00 +0000 |
| 627 |
let expected = "1997-01-01 00:00:00[UTC]".parse::<Zoned>().unwrap(); |
| 628 |
|
| 629 |
for s in [ |
| 630 |
"1997-01-01 00:00:00 +0000", |
| 631 |
"1997-01-01 00:00:00 +00", |
| 632 |
"1997-01-01 00:00 +0000", |
| 633 |
"1997-01-01 00:00:00 +0000", |
| 634 |
"1997-01-01T00:00:00+0000", |
| 635 |
"1997-01-01T00:00:00+00", |
| 636 |
"1997-01-01T00:00:00Z", |
| 637 |
"@852076800", |
| 638 |
] { |
| 639 |
let actual = crate::parse_datetime(s).unwrap(); |
| 640 |
assert_eq!(actual, expected); |
| 641 |
} |
| 642 |
} |
| 643 |
|
| 644 |
#[test] |
| 645 |
fn test_parse_datetime_notz_nodelta() { |
| 646 |
let expected = Zoned::now() |
| 647 |
.with() |
| 648 |
.date(date(1997, 1, 1)) |
| 649 |
.time(time(0, 0, 0, 0)) |
| 650 |
.build() |
| 651 |
.unwrap(); |
| 652 |
|
| 653 |
for s in [ |
| 654 |
"1997-01-01 00:00:00.000000000", |
| 655 |
"Wed Jan 1 00:00:00 1997", |
| 656 |
"1997-01-01T00:00:00", |
| 657 |
"1997-01-01 00:00:00", |
| 658 |
"1997-01-01 00:00", |
| 659 |
] { |
| 660 |
let actual = crate::parse_datetime(s).unwrap(); |
| 661 |
assert_eq!(actual, expected); |
| 662 |
} |
| 663 |
} |
| 664 |
|
| 665 |
#[test] |
| 666 |
fn test_parse_date_notz_nodelta() { |
| 667 |
let expected = Zoned::now() |
| 668 |
.with() |
| 669 |
.date(date(1997, 1, 1)) |
| 670 |
.time(time(0, 0, 0, 0)) |
| 671 |
.build() |
| 672 |
.unwrap(); |
| 673 |
|
| 674 |
for s in ["1997-01-01", "19970101", "01/01/1997", "01/01/97"] { |
| 675 |
let actual = crate::parse_datetime(s).unwrap(); |
| 676 |
assert_eq!(actual, expected); |
| 677 |
} |
| 678 |
} |
| 679 |
|
| 680 |
#[test] |
| 681 |
fn test_parse_datetime_tz_delta() { |
| 682 |
// 1998-01-01 |
| 683 |
let expected = "1998-01-01 00:00:00[UTC]".parse::<Zoned>().unwrap(); |
| 684 |
|
| 685 |
for s in [ |
| 686 |
"1997-01-01 00:00:00 +0000 +1 year", |
| 687 |
"1997-01-01 00:00:00 +00 +1 year", |
| 688 |
"1997-01-01T00:00:00Z +1 year", |
| 689 |
"1997-01-01 00:00 +0000 +1 year", |
| 690 |
"1997-01-01 00:00:00 +0000 +1 year", |
| 691 |
"1997-01-01T00:00:00+0000 +1 year", |
| 692 |
"1997-01-01T00:00:00+00 +1 year", |
| 693 |
] { |
| 694 |
let actual = crate::parse_datetime(s).unwrap(); |
| 695 |
assert_eq!(actual, expected); |
| 696 |
} |
| 697 |
} |
| 698 |
|
| 699 |
#[test] |
| 700 |
fn test_parse_datetime_notz_delta() { |
| 701 |
let expected = Zoned::now() |
| 702 |
.with() |
| 703 |
.date(date(1998, 1, 1)) |
| 704 |
.time(time(0, 0, 0, 0)) |
| 705 |
.build() |
| 706 |
.unwrap(); |
| 707 |
|
| 708 |
for s in [ |
| 709 |
"1997-01-01 00:00:00.000000000 1 year", |
| 710 |
"Wed Jan 1 00:00:00 1997 1 year", |
| 711 |
"1997-01-01T00:00:00 1 year", |
| 712 |
"1997-01-01 00:00:00 1 year", |
| 713 |
"1997-01-01 00:00 1 year", |
| 714 |
] { |
| 715 |
let actual = crate::parse_datetime(s).unwrap(); |
| 716 |
assert_eq!(actual, expected); |
| 717 |
} |
| 718 |
} |
| 719 |
|
| 720 |
#[test] |
| 721 |
fn test_parse_invalid_datetime_notz_delta() { |
| 722 |
// GNU date does not accept the following formats. |
| 723 |
for s in ["199701010000.00 +1 year", "199701010000 +1 year"] { |
| 724 |
assert!(crate::parse_datetime(s).is_err()); |
| 725 |
} |
| 726 |
} |
| 727 |
|
| 728 |
#[test] |
| 729 |
fn test_parse_date_notz_delta() { |
| 730 |
let expected = Zoned::now() |
| 731 |
.with() |
| 732 |
.date(date(1998, 1, 1)) |
| 733 |
.time(time(0, 0, 0, 0)) |
| 734 |
.build() |
| 735 |
.unwrap(); |
| 736 |
|
| 737 |
for s in [ |
| 738 |
"1997-01-01 +1 year", |
| 739 |
"19970101 +1 year", |
| 740 |
"01/01/1997 +1 year", |
| 741 |
"01/01/97 +1 year", |
| 742 |
] { |
| 743 |
let actual = crate::parse_datetime(s).unwrap(); |
| 744 |
assert_eq!(actual, expected); |
| 745 |
} |
| 746 |
} |
| 747 |
|
| 748 |
/// GNU `date` accepts bare `ut` / `UT` as a synonym for UTC (issue #280). |
| 749 |
/// `gmt` and `GMT` already worked; this test covers all four forms. |
| 750 |
#[test] |
| 751 |
fn test_bare_utc_timezone_abbreviations() { |
| 752 |
// All four should parse without error and produce a result in UTC (+00:00). |
| 753 |
for abbr in ["ut", "UT", "gmt", "GMT"] { |
| 754 |
let result = parse_datetime(abbr) |
| 755 |
.unwrap_or_else(|_| panic!("bare timezone '{abbr}' should be accepted")); |
| 756 |
let offset_secs = result.expect_in_range().offset().seconds(); |
| 757 |
assert_eq!(offset_secs, 0, "'{abbr}' should resolve to UTC (+0)"); |
| 758 |
} |
| 759 |
} |
| 760 |
|
| 761 |
#[test] |
| 762 |
fn test_weekday_only() { |
| 763 |
let now = Zoned::now(); |
| 764 |
let midnight = Time::new(0, 0, 0, 0).unwrap(); |
| 765 |
let today = now.weekday(); |
| 766 |
let midnight_today = now.with().time(midnight).build().unwrap(); |
| 767 |
|
| 768 |
for (s, day) in [ |
| 769 |
("sunday", Weekday::Sunday), |
| 770 |
("monday", Weekday::Monday), |
| 771 |
("tuesday", Weekday::Tuesday), |
| 772 |
("wednesday", Weekday::Wednesday), |
| 773 |
("thursday", Weekday::Thursday), |
| 774 |
("friday", Weekday::Friday), |
| 775 |
("saturday", Weekday::Saturday), |
| 776 |
] { |
| 777 |
let actual = parse_datetime(s).unwrap(); |
| 778 |
let delta = day.since(today); |
| 779 |
let expected = midnight_today.checked_add(delta.days()).unwrap(); |
| 780 |
assert_eq!(actual, expected); |
| 781 |
} |
| 782 |
} |
| 783 |
|
| 784 |
mod test_relative { |
| 785 |
use crate::parse_datetime; |
| 786 |
|
| 787 |
#[test] |
| 788 |
fn test_month() { |
| 789 |
assert_eq!( |
| 790 |
parse_datetime("28 feb + 1 month") |
| 791 |
.expect("parse_datetime") |
| 792 |
.expect_in_range() |
| 793 |
.strftime("%m%d") |
| 794 |
.to_string(), |
| 795 |
"0328" |
| 796 |
); |
| 797 |
|
| 798 |
// 29 feb 2025 is invalid |
| 799 |
assert!(parse_datetime("29 feb + 1 year").is_err()); |
| 800 |
|
| 801 |
// 29 feb 2025 is an invalid date |
| 802 |
assert!(parse_datetime("29 feb 2025").is_err()); |
| 803 |
|
| 804 |
// because 29 feb 2025 is invalid, 29 feb 2025 + 1 day is invalid |
| 805 |
// arithmetic does not operate on invalid dates |
| 806 |
assert!(parse_datetime("29 feb 2025 + 1 day").is_err()); |
| 807 |
|
| 808 |
// 28 feb 2023 + 1 day = 1 mar |
| 809 |
assert_eq!( |
| 810 |
parse_datetime("28 feb 2023 + 1 day") |
| 811 |
.unwrap() |
| 812 |
.expect_in_range() |
| 813 |
.strftime("%m%d") |
| 814 |
.to_string(), |
| 815 |
"0301" |
| 816 |
); |
| 817 |
} |
| 818 |
|
| 819 |
#[test] |
| 820 |
fn month_overflow() { |
| 821 |
assert_eq!( |
| 822 |
parse_datetime("2024-01-31 + 1 month") |
| 823 |
.unwrap() |
| 824 |
.expect_in_range() |
| 825 |
.strftime("%Y-%m-%dT%H:%M:%S") |
| 826 |
.to_string(), |
| 827 |
"2024-03-02T00:00:00", |
| 828 |
); |
| 829 |
|
| 830 |
assert_eq!( |
| 831 |
parse_datetime("2024-02-29 + 1 month") |
| 832 |
.unwrap() |
| 833 |
.expect_in_range() |
| 834 |
.strftime("%Y-%m-%dT%H:%M:%S") |
| 835 |
.to_string(), |
| 836 |
"2024-03-29T00:00:00", |
| 837 |
); |
| 838 |
} |
| 839 |
} |
| 840 |
|
| 841 |
mod test_gnu { |
| 842 |
use crate::parse_datetime; |
| 843 |
|
| 844 |
#[test] |
| 845 |
fn gnu_compat() { |
| 846 |
const FMT: &str = "%Y-%m-%d %H:%M:%S"; |
| 847 |
let input = "0000-03-02 00:00:00"; |
| 848 |
assert_eq!( |
| 849 |
input, |
| 850 |
parse_datetime(input) |
| 851 |
.unwrap() |
| 852 |
.expect_in_range() |
| 853 |
.strftime(FMT) |
| 854 |
.to_string() |
| 855 |
); |
| 856 |
|
| 857 |
let input = "2621-03-10 00:00:00"; |
| 858 |
assert_eq!( |
| 859 |
input, |
| 860 |
parse_datetime(input) |
| 861 |
.unwrap() |
| 862 |
.expect_in_range() |
| 863 |
.strftime(FMT) |
| 864 |
.to_string() |
| 865 |
); |
| 866 |
|
| 867 |
let input = "1038-03-10 00:00:00"; |
| 868 |
assert_eq!( |
| 869 |
input, |
| 870 |
parse_datetime(input) |
| 871 |
.unwrap() |
| 872 |
.expect_in_range() |
| 873 |
.strftime(FMT) |
| 874 |
.to_string() |
| 875 |
); |
| 876 |
} |
| 877 |
} |
| 878 |
|
| 879 |
#[cfg(test)] |
| 880 |
mod display { |
| 881 |
use jiff::{civil::DateTime, tz::TimeZone}; |
| 882 |
|
| 883 |
use crate::{parse_datetime_at_date, ExtendedDateTime, ParsedDateTime}; |
| 884 |
|
| 885 |
#[test] |
| 886 |
fn in_range_without_nanoseconds() { |
| 887 |
let base = "2024-06-15 08:30:00" |
| 888 |
.parse::<DateTime>() |
| 889 |
.unwrap() |
| 890 |
.to_zoned(TimeZone::UTC) |
| 891 |
.unwrap(); |
| 892 |
let parsed = parse_datetime_at_date(base, "2024-06-15 08:30:00").unwrap(); |
| 893 |
assert_eq!(parsed.to_string(), "2024-06-15 08:30:00+00:00"); |
| 894 |
} |
| 895 |
|
| 896 |
#[test] |
| 897 |
fn in_range_with_nanoseconds() { |
| 898 |
let base = "2024-06-15 08:30:00.123456789" |
| 899 |
.parse::<DateTime>() |
| 900 |
.unwrap() |
| 901 |
.to_zoned(TimeZone::UTC) |
| 902 |
.unwrap(); |
| 903 |
// Parsing "now" at a base with subsecond precision preserves it. |
| 904 |
let parsed = parse_datetime_at_date(base, "now").unwrap(); |
| 905 |
assert_eq!(parsed.to_string(), "2024-06-15 08:30:00.123456789+00:00"); |
| 906 |
} |
| 907 |
|
| 908 |
#[test] |
| 909 |
fn extended_without_nanoseconds() { |
| 910 |
let dt = ExtendedDateTime::new( |
| 911 |
crate::DateParts { |
| 912 |
year: 12000, |
| 913 |
month: 3, |
| 914 |
day: 15, |
| 915 |
}, |
| 916 |
crate::TimeParts { |
| 917 |
hour: 10, |
| 918 |
minute: 30, |
| 919 |
second: 45, |
| 920 |
nanosecond: 0, |
| 921 |
}, |
| 922 |
3600, |
| 923 |
) |
| 924 |
.unwrap(); |
| 925 |
assert_eq!( |
| 926 |
ParsedDateTime::Extended(dt).to_string(), |
| 927 |
"12000-03-15 10:30:45+01:00" |
| 928 |
); |
| 929 |
} |
| 930 |
|
| 931 |
#[test] |
| 932 |
fn extended_with_nanoseconds() { |
| 933 |
let dt = ExtendedDateTime::new( |
| 934 |
crate::DateParts { |
| 935 |
year: 12000, |
| 936 |
month: 3, |
| 937 |
day: 15, |
| 938 |
}, |
| 939 |
crate::TimeParts { |
| 940 |
hour: 10, |
| 941 |
minute: 30, |
| 942 |
second: 45, |
| 943 |
nanosecond: 123456789, |
| 944 |
}, |
| 945 |
-18000, |
| 946 |
) |
| 947 |
.unwrap(); |
| 948 |
assert_eq!( |
| 949 |
ParsedDateTime::Extended(dt).to_string(), |
| 950 |
"12000-03-15 10:30:45.123456789-05:00" |
| 951 |
); |
| 952 |
} |
| 953 |
} |
| 954 |
|
| 955 |
mod unix_epoch_second { |
| 956 |
use jiff::{civil::DateTime, tz::TimeZone}; |
| 957 |
|
| 958 |
use crate::{parse_datetime, parse_datetime_at_date, DateParts, ParsedDateTime, TimeParts}; |
| 959 |
|
| 960 |
fn epoch_second(input: &str) -> (i64, i32) { |
| 961 |
let base = "2024-01-01 00:00:00" |
| 962 |
.parse::<DateTime>() |
| 963 |
.unwrap() |
| 964 |
.to_zoned(TimeZone::UTC) |
| 965 |
.unwrap(); |
| 966 |
let parsed = parse_datetime_at_date(base, input).unwrap(); |
| 967 |
(parsed.unix_epoch_second(), parsed.subsec_nanosecond()) |
| 968 |
} |
| 969 |
|
| 970 |
#[test] |
| 971 |
fn positive_integer_epoch() { |
| 972 |
let (sec, nsec) = epoch_second("@1690466034"); |
| 973 |
assert_eq!(sec, 1690466034); |
| 974 |
assert_eq!(nsec, 0); |
| 975 |
} |
| 976 |
|
| 977 |
#[test] |
| 978 |
fn positive_fractional_epoch() { |
| 979 |
let (sec, nsec) = epoch_second("@1690466034.5"); |
| 980 |
assert_eq!(sec, 1690466034); |
| 981 |
assert_eq!(nsec, 500_000_000); |
| 982 |
} |
| 983 |
|
| 984 |
#[test] |
| 985 |
fn negative_integer_epoch() { |
| 986 |
let (sec, nsec) = epoch_second("@-1"); |
| 987 |
assert_eq!(sec, -1); |
| 988 |
assert_eq!(nsec, 0); |
| 989 |
} |
| 990 |
|
| 991 |
#[test] |
| 992 |
fn negative_fractional_epoch_floors() { |
| 993 |
// Issue #283: @-1.5 must floor to -2, not truncate to -1. |
| 994 |
let (sec, nsec) = epoch_second("@-1.5"); |
| 995 |
assert_eq!(sec, -2, "floor(-1.5) should be -2, not -1"); |
| 996 |
assert_eq!(nsec, 500_000_000); |
| 997 |
} |
| 998 |
|
| 999 |
#[test] |
| 1000 |
fn negative_fractional_epoch_large() { |
| 1001 |
// From issue #283: @-893375784.554767216 |
| 1002 |
let (sec, nsec) = epoch_second("@-893375784.554767216"); |
| 1003 |
assert_eq!(sec, -893375785); |
| 1004 |
assert_eq!(nsec, 445_232_784); |
| 1005 |
} |
| 1006 |
|
| 1007 |
#[test] |
| 1008 |
fn zero_epoch() { |
| 1009 |
let (sec, nsec) = epoch_second("@0"); |
| 1010 |
assert_eq!(sec, 0); |
| 1011 |
assert_eq!(nsec, 0); |
| 1012 |
} |
| 1013 |
|
| 1014 |
#[test] |
| 1015 |
fn negative_zero_fractional() { |
| 1016 |
// @-0.5 should floor to -1 |
| 1017 |
let (sec, nsec) = epoch_second("@-0.5"); |
| 1018 |
assert_eq!(sec, -1); |
| 1019 |
assert_eq!(nsec, 500_000_000); |
| 1020 |
} |
| 1021 |
|
| 1022 |
#[test] |
| 1023 |
fn extended_values_use_extended_epoch_path() { |
| 1024 |
let parsed = parse_datetime("10000-01-01").unwrap(); |
| 1025 |
// Year 10000 is beyond jiff::Zoned's representable range, so |
| 1026 |
// parse_datetime must route through the ExtendedDateTime branch |
| 1027 |
// of both accessors. |
| 1028 |
assert!(matches!(parsed, ParsedDateTime::Extended(_))); |
| 1029 |
assert_eq!(parsed.subsec_nanosecond(), 0); |
| 1030 |
|
| 1031 |
// Year 10000 UTC in seconds since 1970 is well past 2.5e11. |
| 1032 |
assert!(parsed.unix_epoch_second() > 250_000_000_000); |
| 1033 |
} |
| 1034 |
|
| 1035 |
#[test] |
| 1036 |
fn manually_constructed_extended_values_use_extended_epoch_path() { |
| 1037 |
let ext = crate::ExtendedDateTime::new( |
| 1038 |
DateParts { |
| 1039 |
year: 10_000, |
| 1040 |
month: 1, |
| 1041 |
day: 1, |
| 1042 |
}, |
| 1043 |
TimeParts { |
| 1044 |
hour: 12, |
| 1045 |
minute: 34, |
| 1046 |
second: 56, |
| 1047 |
nanosecond: 789_000_000, |
| 1048 |
}, |
| 1049 |
0, |
| 1050 |
) |
| 1051 |
.unwrap(); |
| 1052 |
let parsed = ParsedDateTime::Extended(ext.clone()); |
| 1053 |
|
| 1054 |
assert_eq!(parsed.unix_epoch_second(), ext.unix_seconds()); |
| 1055 |
assert_eq!(parsed.subsec_nanosecond(), 0); |
| 1056 |
} |
| 1057 |
} |
| 1058 |
} |