Debian Codegraph @

tests/by-util/test_date.rs

raw
1 // This file is part of the uutils coreutils package.
2 //
3 // For the full copyright and license information, please view the LICENSE
4 // file that was distributed with this source code.
5
6 //
7 // spell-checker: ignore: AEDT AEST EEST NZDT NZST Kolkata Iseconds févr février janv janvier mercredi samedi sommes juin décembre Januar Juni Dezember enero junio diciembre gennaio giugno dicembre junho dezembro lundi dimanche Montag Sonntag Samstag sábado febr MEST MESZ KST uueuu ueuu vasárnap június január distros
8 // spell-checker: ignore: uppercases
9
10 use std::cmp::Ordering;
11
12 use jiff::tz::TimeZone;
13 use jiff::{Timestamp, ToSpan};
14 use regex::Regex;
15 #[cfg(all(unix, not(target_vendor = "apple")))]
16 use rustix::process::geteuid;
17 use uutests::util::TestScenario;
18 #[cfg(unix)]
19 use uutests::util::is_locale_available;
20 use uutests::{at_and_ucmd, new_ucmd, util_name};
21
22 #[test]
23 fn test_invalid_arg() {
24 new_ucmd!().arg("--definitely-invalid").fails_with_code(1);
25 }
26
27 #[test]
28 fn test_empty_arguments() {
29 new_ucmd!().arg("").fails_with_code(1);
30 new_ucmd!().args(&["", ""]).fails_with_code(1);
31 new_ucmd!().args(&["", "", ""]).fails_with_code(1);
32 }
33
34 #[test]
35 fn test_extra_operands() {
36 new_ucmd!()
37 .args(&["test", "extra"])
38 .fails_with_code(1)
39 .stderr_contains("extra operand 'extra'");
40 }
41
42 #[test]
43 fn test_bad_format_option_missing_leading_plus_after_d_flag() {
44 let bad_arguments = vec!["q", "a", "test", "%Y-%m-%d"];
45
46 for bad_argument in bad_arguments {
47 new_ucmd!()
48 .args(&["--date", "1996-01-31", bad_argument])
49 .fails_with_code(1)
50 .stderr_contains(format!("the argument {bad_argument} lacks a leading '+';\nwhen using an option to specify date(s), any non-option\nargument must be a format string beginning with '+'"), );
51 }
52 }
53
54 #[test]
55 fn test_invalid_long_option() {
56 new_ucmd!()
57 .arg("--fB")
58 .fails_with_code(1)
59 .stderr_contains("unexpected argument '--fB'");
60 }
61
62 #[test]
63 fn test_invalid_short_option() {
64 new_ucmd!()
65 .arg("-w")
66 .fails_with_code(1)
67 .stderr_contains("unexpected argument '-w'");
68 }
69
70 #[test]
71 fn test_large_year_default_output() {
72 new_ucmd!()
73 .env("LANG", "C")
74 .env("LC_ALL", "C")
75 .env("TZ", "UTC0")
76 .args(&["-d", "18978-01-01"])
77 .succeeds()
78 .stdout_is("Thu Jan 1 00:00:00 UTC 18978\n");
79 }
80
81 #[test]
82 fn test_large_year_default_output_boundary() {
83 for (input, expected) in [
84 ("9999-01-01", "Fri Jan 1 00:00:00 UTC 9999\n"),
85 ("10000-01-01", "Sat Jan 1 00:00:00 UTC 10000\n"),
86 ("10000-01-01 00:00 +1400", "Fri Dec 31 10:00:00 UTC 9999\n"),
87 ("9999-12-31 23:00 -1400", "Sat Jan 1 13:00:00 UTC 10000\n"),
88 ] {
89 new_ucmd!()
90 .env("LC_ALL", "C")
91 .env("TZ", "UTC0")
92 .args(&["-d", input])
93 .succeeds()
94 .stdout_is(expected);
95 }
96
97 new_ucmd!()
98 .env("LC_ALL", "C")
99 .env("TZ", "UTC0")
100 .args(&["-d", "10000-02-30"])
101 .fails_with_code(1)
102 .stderr_contains("invalid date");
103 }
104
105 #[test]
106 fn test_date_rejects_input_that_cannot_take_a_timezone() {
107 // A trailing timezone abbreviation must not rescue an input that already
108 // carries zone information, or that cannot take a zone at all. GNU date
109 // rejects all of these.
110 for input in [
111 "Jan 23 6:00PM GMT-1 EST", // offset plus abbreviation
112 "023-060 MEST", // time with offset, plus abbreviation
113 "2024-01-15 12:00 EST EST", // the same abbreviation twice
114 "@0 EST", // a timestamp cannot take a zone
115 "2024-01-15 12:00 UTC EST", // a named zone whose offset matches TZ
116 "2024-01-15 12:00 GMT EST", // likewise, spelled differently
117 "2024-01-15 12:00 +0000 EST", // a numeric offset matching TZ
118 "2024-01-15 12:00 -0500 EST", // a standalone negative offset
119 "UTC 2024-01-15 12:00 EST", // zone stated before the date
120 ] {
121 new_ucmd!()
122 .env("LC_ALL", "C")
123 .env("TZ", "UTC0")
124 .args(&["-d", input])
125 .fails_with_code(1)
126 .stderr_contains("invalid date");
127 }
128 }
129
130 #[test]
131 fn test_date_accepts_gnu_timezone_abbreviations() {
132 // Abbreviations GNU date accepts, with the UTC time they map to.
133 for (input, expected) in [
134 ("2024-01-15 12:00 MEZ", "11:00\n"),
135 ("2024-01-15 12:00 MESZ", "10:00\n"),
136 ("2024-01-15 12:00 MEST", "10:00\n"),
137 ("2024-01-15 12:00 KST", "03:00\n"),
138 ("2024-01-15 12:00 EST", "17:00\n"),
139 ("2024-01-15 12:00 IST", "06:30\n"),
140 ] {
141 new_ucmd!()
142 .env("LC_ALL", "C")
143 .env("TZ", "UTC0")
144 .args(&["-u", "-d", input, "+%H:%M"])
145 .succeeds()
146 .stdout_is(expected);
147 }
148 }
149
150 #[test]
151 fn test_format_option_not_to_capture_other_valid_arguments() {
152 new_ucmd!()
153 .arg("+%Y%m%d%H%M%S")
154 .arg("--date")
155 .arg("@1770996496")
156 .succeeds();
157 }
158
159 #[test]
160 fn test_single_dash_as_date() {
161 new_ucmd!()
162 .arg("-")
163 .fails_with_code(1)
164 .stderr_contains("invalid date");
165 }
166
167 #[test]
168 fn test_single_dash_as_date_string() {
169 new_ucmd!()
170 .args(&["-u", "-d", "-", "+%T"])
171 .succeeds()
172 .stdout_is("00:00:00\n");
173 }
174
175 #[test]
176 fn test_date_email() {
177 for param in ["--rfc-email", "--rfc-e", "-R", "--rfc-2822", "--rfc-822"] {
178 new_ucmd!().arg(param).succeeds();
179 }
180 }
181
182 #[test]
183 fn test_date_email_multiple_aliases() {
184 // Test that multiple RFC email aliases can be used together
185 // This matches GNU behavior where all aliases map to the same option
186 new_ucmd!()
187 .arg("--rfc-email")
188 .arg("--rfc-822")
189 .arg("--rfc-2822")
190 .succeeds();
191 }
192
193 #[test]
194 #[cfg(unix)]
195 fn test_date_rfc_822_uses_english() {
196 // RFC-822/RFC-2822/RFC-5322 formats should always use English day/month names
197 // regardless of locale (per RFC specification)
198 let scene = TestScenario::new(util_name!());
199
200 // Test with German locale - should still output "Sun" not "So"
201 scene
202 .ucmd()
203 .env("LC_ALL", "de_DE.UTF-8")
204 .env("TZ", "UTC")
205 .args(&["-R", "-d", "1997-01-19 08:17:48 +0"])
206 .succeeds()
207 .stdout_contains("Sun, 19 Jan 1997");
208
209 // Test with French locale - should still output "Sun" not "dim."
210 scene
211 .ucmd()
212 .env("LC_ALL", "fr_FR.UTF-8")
213 .env("TZ", "UTC")
214 .args(&["-R", "-d", "1997-01-19 08:17:48 +0"])
215 .succeeds()
216 .stdout_contains("Sun, 19 Jan 1997");
217 }
218
219 #[test]
220 fn test_date_rfc_3339() {
221 let scene = TestScenario::new(util_name!());
222
223 let rfc_regexp = concat!(
224 r#"(\d+)-(0[1-9]|1[012])-(0[1-9]|[12]\d|3[01])\s([01]\d|2[0-3]):"#,
225 r#"([0-5]\d):([0-5]\d|60)(\.\d+)?(([Zz])|([\+|\-]([01]\d|2[0-3])))"#
226 );
227 let re = Regex::new(rfc_regexp).unwrap();
228
229 // Check that the output matches the regexp
230 for param in ["--rfc-3339", "--rfc-3"] {
231 scene
232 .ucmd()
233 .arg(format!("{param}=ns"))
234 .succeeds()
235 .stdout_matches(&re);
236
237 scene
238 .ucmd()
239 .arg(format!("{param}=seconds"))
240 .succeeds()
241 .stdout_matches(&re);
242 }
243 }
244
245 #[test]
246 fn test_date_rfc_3339_invalid_arg() {
247 for param in ["--iso-3339", "--rfc-3"] {
248 new_ucmd!().arg(format!("{param}=foo")).fails();
249 }
250 }
251
252 #[test]
253 fn test_date_rfc_8601_default() {
254 let re = Regex::new(r"^\d{4}-\d{2}-\d{2}\n$").unwrap();
255 for param in ["--iso-8601", "--i"] {
256 new_ucmd!().arg(param).succeeds().stdout_matches(&re);
257 }
258 }
259
260 #[test]
261 fn test_date_rfc_8601() {
262 let re = Regex::new(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2},\d{9}[+-]\d{2}:\d{2}\n$").unwrap();
263 for param in ["--iso-8601", "--i"] {
264 new_ucmd!()
265 .arg(format!("{param}=ns"))
266 .succeeds()
267 .stdout_matches(&re);
268 }
269 }
270
271 #[test]
272 fn test_date_rfc_8601_invalid_arg() {
273 for param in ["--iso-8601", "--i"] {
274 new_ucmd!().arg(format!("{param}=@")).fails();
275 }
276 }
277
278 #[test]
279 fn test_date_rfc_8601_second() {
280 let re = Regex::new(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{2}:\d{2}\n$").unwrap();
281 for param in ["--iso-8601", "--i"] {
282 new_ucmd!()
283 .arg(format!("{param}=second"))
284 .succeeds()
285 .stdout_matches(&re);
286 new_ucmd!()
287 .arg(format!("{param}=seconds"))
288 .succeeds()
289 .stdout_matches(&re);
290 }
291 }
292
293 #[test]
294 fn test_date_rfc_8601_minute() {
295 let re = Regex::new(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}[+-]\d{2}:\d{2}\n$").unwrap();
296 for param in ["--iso-8601", "--i"] {
297 new_ucmd!()
298 .arg(format!("{param}=minute"))
299 .succeeds()
300 .stdout_matches(&re);
301 new_ucmd!()
302 .arg(format!("{param}=minutes"))
303 .succeeds()
304 .stdout_matches(&re);
305 }
306 }
307
308 #[test]
309 fn test_date_rfc_8601_hour() {
310 let re = Regex::new(r"^\d{4}-\d{2}-\d{2}T\d{2}[+-]\d{2}:\d{2}\n$").unwrap();
311 for param in ["--iso-8601", "--i"] {
312 new_ucmd!()
313 .arg(format!("{param}=hour"))
314 .succeeds()
315 .stdout_matches(&re);
316 new_ucmd!()
317 .arg(format!("{param}=hours"))
318 .succeeds()
319 .stdout_matches(&re);
320 }
321 }
322
323 #[test]
324 fn test_date_rfc_8601_date() {
325 let re = Regex::new(r"^\d{4}-\d{2}-\d{2}\n$").unwrap();
326 for param in ["--iso-8601", "--i"] {
327 new_ucmd!()
328 .arg(format!("{param}=date"))
329 .succeeds()
330 .stdout_matches(&re);
331 }
332 }
333
334 #[test]
335 fn test_date_utc() {
336 for param in ["--universal", "--utc", "--uct", "--uni", "--u"] {
337 new_ucmd!().arg(param).succeeds();
338 }
339 }
340
341 #[test]
342 fn test_date_utc_multiple_aliases() {
343 // Test that multiple UTC aliases can be used together
344 // This matches GNU behavior where all aliases map to the same option
345 new_ucmd!()
346 .arg("--uct")
347 .arg("--utc")
348 .arg("--universal")
349 .succeeds();
350 }
351
352 #[test]
353 fn test_date_utc_issue_6495() {
354 new_ucmd!()
355 .env("TZ", "UTC0")
356 .arg("-u")
357 .arg("-d")
358 .arg("@0")
359 .succeeds()
360 .stdout_is("Thu Jan 1 00:00:00 UTC 1970\n");
361 }
362
363 #[test]
364 fn test_date_utc_with_d_flag() {
365 let cases = [
366 ("2024-01-01 12:00", "+%H:%M %Z", "12:00 UTC\n"),
367 ("2024-06-15 10:30", "+%H:%M %Z", "10:30 UTC\n"),
368 ("2024-12-31 23:59:59", "+%H:%M:%S %Z", "23:59:59 UTC\n"),
369 ("@0", "+%Y-%m-%d %H:%M:%S %Z", "1970-01-01 00:00:00 UTC\n"),
370 ("@3600", "+%H:%M:%S %Z", "01:00:00 UTC\n"),
371 ("@86400", "+%Y-%m-%d %Z", "1970-01-02 UTC\n"),
372 ("2024-06-15 10:30 EDT", "+%H:%M %Z", "14:30 UTC\n"),
373 ("2024-01-15 10:30 EST", "+%H:%M %Z", "15:30 UTC\n"),
374 ("2024-06-15 12:00 PDT", "+%H:%M %Z", "19:00 UTC\n"),
375 ("2024-01-15 12:00 PST", "+%H:%M %Z", "20:00 UTC\n"),
376 ("2024-01-01 12:00 +0000", "+%H:%M %Z", "12:00 UTC\n"),
377 ("2024-01-01 12:00 +0530", "+%H:%M %Z", "06:30 UTC\n"),
378 ("2024-01-01 12:00 -0500", "+%H:%M %Z", "17:00 UTC\n"),
379 ];
380 for (input, fmt, expected) in cases {
381 new_ucmd!()
382 .env("TZ", "America/New_York")
383 .args(&["-u", "-d", input, fmt])
384 .succeeds()
385 .stdout_is(expected);
386 }
387 }
388
389 #[test]
390 fn test_date_utc_vs_local() {
391 let cases = [
392 ("-d", "2024-01-01 12:00", "+%H:%M %Z", "12:00 EST\n"),
393 ("-ud", "2024-01-01 12:00", "+%H:%M %Z", "12:00 UTC\n"),
394 ("-d", "2024-06-15 12:00", "+%H:%M %Z", "12:00 EDT\n"),
395 ("-ud", "2024-06-15 12:00", "+%H:%M %Z", "12:00 UTC\n"),
396 ("-d", "@0", "+%H:%M %Z", "19:00 EST\n"),
397 ("-ud", "@0", "+%H:%M %Z", "00:00 UTC\n"),
398 ];
399 for (flag, date, fmt, expected) in cases {
400 new_ucmd!()
401 .env("TZ", "America/New_York")
402 .args(&[flag, date, fmt])
403 .succeeds()
404 .stdout_is(expected);
405 }
406 }
407
408 #[test]
409 fn test_date_utc_output_formats() {
410 let cases = [
411 ("-I", "2024-06-15"),
412 ("--rfc-3339=seconds", "+00:00"),
413 ("-R", "+0000"),
414 ];
415 for (fmt_flag, expected) in cases {
416 new_ucmd!()
417 .env("TZ", "America/New_York")
418 .args(&["-u", "-d", "2024-06-15 12:00", fmt_flag])
419 .succeeds()
420 .stdout_contains(expected);
421 }
422 }
423
424 #[test]
425 fn test_date_utc_stdin() {
426 new_ucmd!()
427 .env("TZ", "America/New_York")
428 .args(&["-u", "-f", "-", "+%H:%M %Z"])
429 .pipe_in("2024-01-01 12:00\n2024-06-15 18:30\n")
430 .succeeds()
431 .stdout_is("12:00 UTC\n18:30 UTC\n");
432 }
433
434 #[test]
435 fn test_date_format_y() {
436 let scene = TestScenario::new(util_name!());
437
438 let mut re = Regex::new(r"^\d{4}\n$").unwrap();
439 scene.ucmd().arg("+%Y").succeeds().stdout_matches(&re);
440
441 re = Regex::new(r"^\d{2}\n$").unwrap();
442 scene.ucmd().arg("+%y").succeeds().stdout_matches(&re);
443 }
444
445 #[test]
446 fn test_date_format_q() {
447 let scene = TestScenario::new(util_name!());
448
449 let re = Regex::new(r"^[1-4]\n$").unwrap();
450 scene.ucmd().arg("+%q").succeeds().stdout_matches(&re);
451 }
452
453 #[test]
454 fn test_date_format_m() {
455 let scene = TestScenario::new(util_name!());
456
457 let mut re = Regex::new(r"\S+").unwrap();
458 scene.ucmd().arg("+%b").succeeds().stdout_matches(&re);
459
460 re = Regex::new(r"^\d{2}\n$").unwrap();
461 scene.ucmd().arg("+%m").succeeds().stdout_matches(&re);
462 }
463
464 #[test]
465 fn test_date_format_day() {
466 let scene = TestScenario::new(util_name!());
467
468 let mut re = Regex::new(r"\S+").unwrap();
469 scene.ucmd().arg("+%a").succeeds().stdout_matches(&re);
470
471 re = Regex::new(r"\S+").unwrap();
472 scene.ucmd().arg("+%A").succeeds().stdout_matches(&re);
473
474 re = Regex::new(r"^\d{1}\n$").unwrap();
475 scene.ucmd().arg("+%u").succeeds().stdout_matches(&re);
476 }
477
478 #[test]
479 fn test_date_format_full_day() {
480 let re = Regex::new(r"\S+ \d{4}-\d{2}-\d{2}").unwrap();
481 new_ucmd!()
482 .arg("+'%a %Y-%m-%d'")
483 .succeeds()
484 .stdout_matches(&re);
485 }
486
487 #[test]
488 fn test_date_issue_3780() {
489 new_ucmd!().arg("+%Y-%m-%d %H-%M-%S%:::z").succeeds();
490 }
491
492 #[test]
493 fn test_date_nano_seconds() {
494 // %N nanoseconds (000000000..999999999)
495 let re = Regex::new(r"^\d{1,9}\n$").unwrap();
496 new_ucmd!().arg("+%N").succeeds().stdout_matches(&re);
497 }
498
499 #[test]
500 fn test_date_format_without_plus() {
501 // [+FORMAT]
502 new_ucmd!()
503 .arg("%s")
504 .fails_with_code(1)
505 .stderr_contains("date: invalid date '%s'");
506 }
507
508 #[test]
509 fn test_date_format_literal() {
510 new_ucmd!().arg("+%%s").succeeds().stdout_is("%s\n");
511 new_ucmd!().arg("+%%N").succeeds().stdout_is("%N\n");
512 }
513
514 #[test]
515 #[cfg(all(unix, not(target_vendor = "apple")))]
516 fn test_date_set_valid() {
517 if geteuid().is_root() {
518 new_ucmd!()
519 .arg("--set")
520 .arg("2020-03-12 13:30:00+08:00")
521 .succeeds()
522 .no_output();
523 }
524 }
525
526 #[test]
527 #[cfg(any(windows, all(unix, not(target_vendor = "apple"))))]
528 fn test_date_set_invalid() {
529 let result = new_ucmd!().arg("--set").arg("123abcd").fails();
530 result.no_stdout();
531 assert!(result.stderr_str().starts_with("date: invalid date "));
532 }
533
534 #[test]
535 #[cfg(all(unix, not(any(target_vendor = "apple", target_os = "android"))))]
536 fn test_date_set_permissions_error() {
537 if !(geteuid().is_root() || uucore::os::is_wsl_1()) {
538 let result = new_ucmd!()
539 .arg("--set")
540 .arg("2020-03-11 21:45:00+08:00")
541 .fails();
542 result.no_stdout();
543 assert!(result.stderr_str().starts_with("date: cannot set date: "));
544 }
545 }
546
547 #[test]
548 #[cfg(all(unix, not(any(target_vendor = "apple", target_os = "android"))))]
549 fn test_date_set_hyphen_prefixed_values() {
550 // test -s flag accepts hyphen-prefixed values like "-3 days"
551 if !(geteuid().is_root() || uucore::os::is_wsl_1()) {
552 let test_cases = vec!["-1 hour", "-2 days", "-3 weeks", "-1 month"];
553
554 for date_str in test_cases {
555 let result = new_ucmd!().arg("--set").arg(date_str).fails();
556 result.no_stdout();
557 // permission error, not argument parsing error
558 assert!(
559 result.stderr_str().starts_with("date: cannot set date: "),
560 "Expected permission error for '{date_str}', but got: {}",
561 result.stderr_str()
562 );
563 }
564 }
565 }
566
567 #[test]
568 #[cfg(target_vendor = "apple")]
569 fn test_date_set_mac_unavailable() {
570 let result = new_ucmd!()
571 .arg("--set")
572 .arg("2020-03-11 21:45:00+08:00")
573 .fails();
574 result.no_stdout();
575 assert!(
576 result
577 .stderr_str()
578 .starts_with("date: setting the date is not supported by macOS")
579 );
580 }
581
582 #[test]
583 #[cfg(all(unix, not(target_vendor = "apple")))]
584 fn test_date_set_valid_2() {
585 if geteuid().is_root() {
586 new_ucmd!()
587 .arg("--set")
588 .arg("Sat 20 Mar 2021 14:53:01 AWST") // spell-checker:disable-line
589 .succeeds()
590 .no_output();
591 }
592 }
593
594 #[test]
595 fn test_date_for_invalid_file() {
596 let result = new_ucmd!().arg("--file").arg("invalid_file").fails();
597 result.no_stdout();
598 assert_eq!(
599 result.stderr_str().trim(),
600 "date: invalid_file: No such file or directory",
601 );
602 }
603
604 #[test]
605 #[cfg(unix)]
606 fn test_date_for_no_permission_file() {
607 use std::os::unix::fs::PermissionsExt;
608 const FILE: &str = "file-no-perm-1";
609
610 let (at, mut ucmd) = at_and_ucmd!();
611
612 let file = std::fs::OpenOptions::new()
613 .create(true)
614 .truncate(true)
615 .write(true)
616 .open(at.plus(FILE))
617 .unwrap();
618 file.set_permissions(std::fs::Permissions::from_mode(0o222))
619 .unwrap();
620 let result = ucmd.arg("--file").arg(FILE).fails();
621 result.no_stdout();
622 assert_eq!(
623 result.stderr_str().trim(),
624 format!("date: {FILE}: Permission denied")
625 );
626 }
627
628 #[test]
629 fn test_date_for_dir_as_file() {
630 let result = new_ucmd!().arg("--file").arg("/").fails_with_code(1);
631 result.no_stdout();
632 assert_eq!(
633 result.stderr_str().trim(),
634 "date: expected file, got directory '/'",
635 );
636 }
637
638 #[test]
639 fn test_date_for_file() {
640 let (at, mut ucmd) = at_and_ucmd!();
641 let file = "test_date_for_file";
642 at.touch(file);
643 ucmd.arg("--file").arg(file).succeeds();
644 }
645
646 #[test]
647 fn test_date_file_invalid_utf8_line() {
648 let (at, mut ucmd) = at_and_ucmd!();
649 let file = "test_date_file_invalid_utf8";
650 // A 0xFF byte makes the whole line invalid UTF-8
651 at.write_bytes(file, b"Hello\xffx\n");
652
653 // GNU date: "date: invalid date 'Hello\377x'" on stderr, exit code 1
654 let result = ucmd.args(&["-u", "-f", file]).fails_with_code(1);
655 result.no_stdout();
656 result.stderr_contains("date: invalid date 'Hello\\377x'");
657 }
658
659 #[test]
660 fn test_date_file_invalid_utf8_line_continues() {
661 let (at, mut ucmd) = at_and_ucmd!();
662 let file = "test_date_file_mixed_invalid_utf8";
663 at.write_bytes(
664 file,
665 b"2024-01-15 12:00:00\nHello\xffx\n2024-01-16 13:00:00\n",
666 );
667
668 // GNU date reports the invalid line but still processes the other lines,
669 // exiting with code 1
670 let result = ucmd.args(&["-u", "-f", file]).fails_with_code(1);
671 result.stdout_contains("Mon Jan 15 12:00:00 UTC 2024");
672 result.stdout_contains("Tue Jan 16 13:00:00 UTC 2024");
673 result.stderr_contains("date: invalid date 'Hello\\377x'");
674 }
675
676 #[test]
677 fn test_date_stdin_invalid_utf8_line() {
678 // `date -f -` reads from stdin through the same path
679 new_ucmd!()
680 .args(&["-u", "-f", "-"])
681 .pipe_in(b"Hello\xffx\n".to_vec())
682 .fails_with_code(1)
683 .stderr_contains("date: invalid date 'Hello\\377x'");
684 }
685
686 #[test]
687 fn test_date_for_file_mtime() {
688 use std::time::{Duration, UNIX_EPOCH};
689
690 let (at, mut ucmd) = at_and_ucmd!();
691
692 let reference_file = "reference_file";
693 let f = at.make_file(reference_file);
694 let modification_date = UNIX_EPOCH.checked_add(Duration::from_secs(1234)).unwrap();
695 f.set_modified(modification_date).unwrap();
696
697 ucmd.arg("--reference")
698 .arg(reference_file)
699 .arg("+%s")
700 .succeeds()
701 .stdout_only("1234\n");
702 }
703
704 #[test]
705 fn test_date_multiple_references() {
706 use std::time::{Duration, UNIX_EPOCH};
707
708 let scene = TestScenario::new(util_name!());
709 let at = &scene.fixtures;
710
711 let create_file = |name: &str, secs: u64| {
712 let f = at.make_file(name);
713 let date = UNIX_EPOCH.checked_add(Duration::from_secs(secs)).unwrap();
714 f.set_modified(date).unwrap();
715 };
716
717 create_file("a", 1111);
718 create_file("b", 2222);
719
720 // last ref "wins"
721 for (refs, expected) in [(["a", "b"], "2222\n"), (["b", "a"], "1111\n")] {
722 scene
723 .ucmd()
724 .args(&["--reference", refs[0], "--reference", refs[1]])
725 .arg("+%s")
726 .succeeds()
727 .stdout_only(expected);
728 }
729 }
730
731 #[test]
732 #[cfg(all(unix, not(target_vendor = "apple")))]
733 fn test_date_set_valid_3() {
734 if geteuid().is_root() {
735 new_ucmd!()
736 .arg("--set")
737 .arg("Sat 20 Mar 2021 14:53:01") // Local timezone
738 .succeeds()
739 .no_output();
740 }
741 }
742
743 #[test]
744 #[cfg(all(unix, not(target_vendor = "apple")))]
745 fn test_date_set_valid_4() {
746 if geteuid().is_root() {
747 new_ucmd!()
748 .arg("--set")
749 .arg("2020-03-11 21:45:00") // Local timezone
750 .succeeds()
751 .no_output();
752 }
753 }
754
755 #[test]
756 fn test_invalid_format_string() {
757 // With lenient mode, invalid format sequences are output literally (like GNU date)
758 new_ucmd!().arg("+%!").succeeds().stdout_is("%!\n");
759 }
760
761 #[test]
762 fn test_invalid_format_string_with_too_many_colons() {
763 new_ucmd!()
764 .arg("+%_::::z")
765 .succeeds()
766 .stdout_is("%_::::z\n");
767 }
768
769 #[test]
770 fn test_capitalized_numeric_time_zone() {
771 // %z +hhmm numeric time zone (e.g., -0400)
772 // # is supposed to capitalize, which makes little sense here, but keep coverage
773 // on such format so it's good to test.
774 let re = Regex::new(r"^[+-]\d{4,4}\n$").unwrap();
775 new_ucmd!().arg("+%#z").succeeds().stdout_matches(&re);
776 }
777
778 #[test]
779 fn test_date_string_human() {
780 let date_formats = vec![
781 "1 year ago",
782 "1 year",
783 "2 months ago",
784 "15 days ago",
785 "1 week ago",
786 "5 hours ago",
787 "30 minutes ago",
788 "10 seconds",
789 "last day",
790 "last monday",
791 "last week",
792 "last month",
793 "last year",
794 "this monday",
795 "next day",
796 "next monday",
797 "next week",
798 "next month",
799 "next year",
800 ];
801 let re = Regex::new(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}\n$").unwrap();
802 for date_format in date_formats {
803 new_ucmd!()
804 .arg("-d")
805 .arg(date_format)
806 .arg("+%Y-%m-%d %S:%M")
807 .succeeds()
808 .stdout_matches(&re);
809 }
810 }
811
812 #[test]
813 fn test_negative_offset() {
814 let data_formats = vec![
815 ("-1 hour", 1.hours()),
816 ("-1 hours", 1.hours()),
817 ("-1 day", 24.hours()),
818 ("-2 weeks", (14 * 24).hours()),
819 ];
820 for (date_format, offset) in data_formats {
821 new_ucmd!()
822 .arg("-d")
823 .arg(date_format)
824 .arg("--rfc-3339=seconds")
825 .succeeds()
826 .stdout_str_check(|out| {
827 let date = out.trim().parse::<Timestamp>().unwrap();
828 // Is the resulting date roughly what is expected?
829 let expected_date = Timestamp::now() - offset;
830 (date - expected_date).abs().compare(10.minutes()).unwrap() == Ordering::Less
831 });
832 }
833 }
834
835 #[test]
836 fn test_relative_weekdays() {
837 // Truncate time component to midnight
838 let today = Timestamp::now().to_zoned(TimeZone::UTC).date();
839 // Loop through each day of the week, starting with today
840 for offset in 0..7 {
841 for direction in ["last", "this", "next"] {
842 let weekday = today
843 .checked_add(offset.days())
844 .unwrap()
845 .strftime("%a")
846 .to_string();
847 new_ucmd!()
848 .arg("-d")
849 .arg(format!("{direction} {weekday}"))
850 .arg("--rfc-3339=seconds")
851 .arg("--utc")
852 .succeeds()
853 .stdout_str_check(|out| {
854 let result = out.trim().parse::<Timestamp>().unwrap();
855 let expected = match (direction, offset) {
856 ("last", _) => today.checked_sub((7 - offset).days()).unwrap(),
857 ("this", 0) => today,
858 ("next", 0) => today.checked_add(7.days()).unwrap(),
859 _ => today.checked_add(offset.days()).unwrap(),
860 };
861 let expected_ts = expected.to_zoned(TimeZone::UTC).unwrap().timestamp();
862 result == expected_ts
863 });
864 }
865 }
866 }
867
868 #[test]
869 fn test_invalid_date_string() {
870 new_ucmd!()
871 .arg("-d")
872 .arg("foo")
873 .fails()
874 .no_stdout()
875 .stderr_contains("invalid date");
876
877 new_ucmd!()
878 .arg("-d")
879 // cSpell:disable
880 .arg("this fooday")
881 // cSpell:enable
882 .fails()
883 .no_stdout()
884 .stderr_contains("invalid date");
885 }
886
887 #[test]
888 fn test_multiple_dates() {
889 new_ucmd!()
890 .arg("-d")
891 .arg("invalid")
892 .arg("-d")
893 .arg("2000-02-02")
894 .arg("+%Y")
895 .succeeds()
896 .stdout_is("2000\n")
897 .no_stderr();
898 }
899
900 #[test]
901 fn test_date_one_digit_date() {
902 new_ucmd!()
903 .env("TZ", "UTC0")
904 .arg("-d")
905 .arg("2000-1-1")
906 .succeeds()
907 .stdout_only("Sat Jan 1 00:00:00 UTC 2000\n");
908
909 new_ucmd!()
910 .env("TZ", "UTC0")
911 .arg("-d")
912 .arg("2000-1-4")
913 .succeeds()
914 .stdout_only("Tue Jan 4 00:00:00 UTC 2000\n");
915 }
916
917 #[test]
918 fn test_date_overflow() {
919 new_ucmd!()
920 .arg("-d68888888888888sms")
921 .fails()
922 .no_stdout()
923 .stderr_contains("invalid date");
924 }
925
926 #[test]
927 fn test_date_parse_from_format() {
928 const FILE: &str = "file-with-dates";
929 let (at, mut ucmd) = at_and_ucmd!();
930
931 at.write(
932 FILE,
933 "2023-03-27 08:30:00\n\
934 2023-04-01 12:00:00\n\
935 2023-04-15 18:30:00",
936 );
937 ucmd.arg("-f")
938 .arg(at.plus(FILE))
939 .arg("+%Y-%m-%d %H:%M:%S")
940 .succeeds();
941 }
942
943 #[test]
944 fn test_date_from_stdin() {
945 new_ucmd!()
946 .env("TZ", "UTC0")
947 .arg("-f")
948 .arg("-")
949 .pipe_in(
950 "2023-03-27 08:30:00\n\
951 2023-04-01 12:00:00\n\
952 2023-04-15 18:30:00\n",
953 )
954 .succeeds()
955 .stdout_is(
956 "Mon Mar 27 08:30:00 UTC 2023\n\
957 Sat Apr 1 12:00:00 UTC 2023\n\
958 Sat Apr 15 18:30:00 UTC 2023\n",
959 );
960 }
961
962 const JAN2: &str = "2024-01-02 12:00:00 +0000";
963 const JUL2: &str = "2024-07-02 12:00:00 +0000";
964
965 #[test]
966 fn test_date_tz() {
967 fn test_tz(tz: &str, date: &str, output: &str) {
968 println!("Test with TZ={tz}, date=\"{date}\".");
969 new_ucmd!()
970 .env("TZ", tz)
971 .arg("-d")
972 .arg(date)
973 .arg("+%Y-%m-%d %H:%M:%S %Z")
974 .succeeds()
975 .stdout_only(output);
976 }
977
978 // Empty TZ, UTC0, invalid timezone.
979 test_tz("", JAN2, "2024-01-02 12:00:00 UTC\n");
980 test_tz("UTC0", JAN2, "2024-01-02 12:00:00 UTC\n");
981 // TODO: We do not handle invalid timezones the same way as GNU coreutils
982 //test_tz("Invalid/Timezone", JAN2, "2024-01-02 12:00:00 Invalid\n");
983
984 // Test various locations, some of them use daylight saving, some don't.
985 test_tz("America/Vancouver", JAN2, "2024-01-02 04:00:00 PST\n");
986 test_tz("America/Vancouver", JUL2, "2024-07-02 05:00:00 PDT\n");
987 test_tz("Europe/Berlin", JAN2, "2024-01-02 13:00:00 CET\n");
988 test_tz("Europe/Berlin", JUL2, "2024-07-02 14:00:00 CEST\n");
989 test_tz("Africa/Cairo", JAN2, "2024-01-02 14:00:00 EET\n");
990 // Egypt restored daylight saving in 2023, so if the database is outdated, this will fail.
991 //test_tz("Africa/Cairo", JUL2, "2024-07-02 15:00:00 EEST\n");
992 test_tz("Asia/Tokyo", JAN2, "2024-01-02 21:00:00 JST\n");
993 test_tz("Asia/Tokyo", JUL2, "2024-07-02 21:00:00 JST\n");
994 test_tz("Australia/Sydney", JAN2, "2024-01-02 23:00:00 AEDT\n");
995 test_tz("Australia/Sydney", JUL2, "2024-07-02 22:00:00 AEST\n"); // Shifts the other way.
996 test_tz("Pacific/Tahiti", JAN2, "2024-01-02 02:00:00 -10\n"); // No abbreviation.
997 test_tz("Pacific/Auckland", JAN2, "2024-01-03 01:00:00 NZDT\n");
998 test_tz("Pacific/Auckland", JUL2, "2024-07-03 00:00:00 NZST\n");
999 }
1000
1001 #[test]
1002 fn test_date_tz_with_utc_flag() {
1003 new_ucmd!()
1004 .env("TZ", "Europe/Berlin")
1005 .arg("-u")
1006 .arg("+%Z")
1007 .succeeds()
1008 .stdout_only("UTC\n");
1009 }
1010
1011 #[test]
1012 fn test_date_tz_various_formats() {
1013 fn test_tz(tz: &str, date: &str, output: &str) {
1014 println!("Test with TZ={tz}, date=\"{date}\".");
1015 new_ucmd!()
1016 .env("TZ", tz)
1017 .arg("-d")
1018 .arg(date)
1019 .arg("+%z %:z %::z %:::z %Z")
1020 .succeeds()
1021 .stdout_only(output);
1022 }
1023
1024 test_tz(
1025 "America/Vancouver",
1026 JAN2,
1027 "-0800 -08:00 -08:00:00 -08 PST\n",
1028 );
1029 // Half-hour timezone
1030 test_tz("Asia/Kolkata", JAN2, "+0530 +05:30 +05:30:00 +05:30 IST\n"); // spell-checker:disable-line
1031 test_tz("Europe/Berlin", JAN2, "+0100 +01:00 +01:00:00 +01 CET\n");
1032 test_tz(
1033 "Australia/Sydney",
1034 JAN2,
1035 "+1100 +11:00 +11:00:00 +11 AEDT\n",
1036 );
1037 }
1038
1039 #[test]
1040 fn test_date_tz_with_relative_time() {
1041 new_ucmd!()
1042 .env("TZ", "America/Vancouver")
1043 .arg("-d")
1044 .arg("1 hour ago")
1045 .arg("+%Y-%m-%d %H:%M:%S %Z")
1046 .succeeds()
1047 .stdout_matches(&Regex::new(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} P[DS]T\n$").unwrap());
1048 }
1049
1050 #[test]
1051 fn test_date_utc_time() {
1052 // Test that -u flag shows correct UTC time
1053 // We get 2 UTC times just in case we're really unlucky and this runs around
1054 // an hour change.
1055 let utc_hour_1: i32 = new_ucmd!()
1056 .env("TZ", "Asia/Taipei")
1057 .arg("-u")
1058 .arg("+%-H")
1059 .succeeds()
1060 .stdout_str()
1061 .trim_end()
1062 .parse()
1063 .unwrap();
1064 let tpe_hour: i32 = new_ucmd!()
1065 .env("TZ", "Asia/Taipei")
1066 .arg("+%-H")
1067 .succeeds()
1068 .stdout_str()
1069 .trim_end()
1070 .parse()
1071 .unwrap();
1072 let utc_hour_2: i32 = new_ucmd!()
1073 .env("TZ", "Asia/Taipei")
1074 .arg("-u")
1075 .arg("+%-H")
1076 .succeeds()
1077 .stdout_str()
1078 .trim_end()
1079 .parse()
1080 .unwrap();
1081 // Taipei is always 8 hours ahead of UTC (no daylight savings)
1082 assert!(
1083 (tpe_hour - utc_hour_1 + 24) % 24 == 8 || (tpe_hour - utc_hour_2 + 24) % 24 == 8,
1084 "TPE: {tpe_hour} UTC: {utc_hour_1}/{utc_hour_2}"
1085 );
1086
1087 // Test that -u flag shows UTC timezone
1088 new_ucmd!()
1089 .arg("-u")
1090 .arg("+%Z")
1091 .succeeds()
1092 .stdout_only("UTC\n");
1093
1094 // Test that -u flag with specific timestamp shows correct UTC time
1095 new_ucmd!()
1096 .arg("-u")
1097 .arg("-d")
1098 .arg("@0")
1099 .succeeds()
1100 .stdout_only("Thu Jan 1 00:00:00 UTC 1970\n");
1101 }
1102
1103 #[test]
1104 fn test_date_empty_tz_time() {
1105 new_ucmd!()
1106 .env("TZ", "")
1107 .arg("-d")
1108 .arg("@0")
1109 .succeeds()
1110 .stdout_only("Thu Jan 1 00:00:00 UTC 1970\n");
1111 }
1112
1113 #[test]
1114 fn test_date_resolution() {
1115 // Test that --resolution flag returns a floating point number by default
1116 new_ucmd!()
1117 .arg("--resolution")
1118 .succeeds()
1119 .stdout_str_check(|s| s.trim().parse::<f64>().is_ok());
1120
1121 // Test that --resolution flag can be passed twice to match gnu
1122 new_ucmd!()
1123 .arg("--resolution")
1124 .arg("--resolution")
1125 .succeeds()
1126 .stdout_str_check(|s| s.trim().parse::<f64>().is_ok());
1127
1128 // Test that can --resolution output can be formatted as a date
1129 new_ucmd!()
1130 .arg("--resolution")
1131 .arg("-Iseconds")
1132 .succeeds()
1133 .stdout_only("1970-01-01T00:00:00+00:00\n");
1134 }
1135
1136 #[test]
1137 fn test_date_resolution_no_combine() {
1138 // Test that date fails when --resolution flag is passed with date flag
1139 new_ucmd!()
1140 .arg("--resolution")
1141 .arg("-d")
1142 .arg("2025-01-01")
1143 .fails();
1144 }
1145
1146 #[test]
1147 fn test_date_numeric_d_basic_utc() {
1148 // Verify GNU-compatible pure-digit parsing for -d STRING under UTC
1149 // 0/00 -> today at 00:00; 7/07 -> today at 07:00; 0700 -> today at 07:00
1150 let today = Timestamp::now().to_zoned(TimeZone::UTC).date();
1151 let yyyy = today.year();
1152 let mm = today.month();
1153 let dd = today.day();
1154
1155 let mk =
1156 |h: u32, m: u32| -> String { format!("{yyyy:04}-{mm:02}-{dd:02} {h:02}:{m:02}:00 UTC\n") };
1157
1158 new_ucmd!()
1159 .env("TZ", "UTC0")
1160 .arg("-d")
1161 .arg("0")
1162 .arg("+%F %T %Z")
1163 .succeeds()
1164 .stdout_only(mk(0, 0));
1165
1166 new_ucmd!()
1167 .env("TZ", "UTC0")
1168 .arg("-d")
1169 .arg("7")
1170 .arg("+%F %T %Z")
1171 .succeeds()
1172 .stdout_only(mk(7, 0));
1173
1174 new_ucmd!()
1175 .env("TZ", "UTC0")
1176 .arg("-d")
1177 .arg("0700")
1178 .arg("+%F %T %Z")
1179 .succeeds()
1180 .stdout_only(mk(7, 0));
1181 }
1182
1183 #[test]
1184 fn test_date_numeric_d_invalid_numbers() {
1185 // Ensure invalid HHMM values are rejected (GNU-compatible)
1186 new_ucmd!()
1187 .env("TZ", "UTC0")
1188 .arg("-d")
1189 .arg("2400")
1190 .arg("+%F %T %Z")
1191 .fails()
1192 .stderr_contains("invalid date");
1193
1194 new_ucmd!()
1195 .env("TZ", "UTC0")
1196 .arg("-d")
1197 .arg("2360")
1198 .arg("+%F %T %Z")
1199 .fails()
1200 .stderr_contains("invalid date");
1201 }
1202
1203 #[test]
1204 fn test_date_tz_abbreviation_utc_gmt() {
1205 // Test UTC and GMT timezone abbreviations
1206 new_ucmd!()
1207 .arg("-d")
1208 .arg("2021-03-20 14:53:01 UTC")
1209 .arg("+%Y-%m-%d %H:%M:%S")
1210 .succeeds();
1211
1212 new_ucmd!()
1213 .arg("-d")
1214 .arg("2021-03-20 14:53:01 GMT")
1215 .arg("+%Y-%m-%d %H:%M:%S")
1216 .succeeds();
1217 }
1218
1219 #[test]
1220 fn test_date_tz_abbreviation_us_timezones() {
1221 // Test US timezone abbreviations (uutils supports, GNU also supports these)
1222 let us_zones = vec![
1223 ("PST", "2021-03-20 14:53:01 PST"),
1224 ("PDT", "2021-03-20 14:53:01 PDT"),
1225 ("MST", "2021-03-20 14:53:01 MST"),
1226 ("MDT", "2021-03-20 14:53:01 MDT"),
1227 ("CST", "2021-03-20 14:53:01 CST"),
1228 ("CDT", "2021-03-20 14:53:01 CDT"),
1229 ("EST", "2021-03-20 14:53:01 EST"),
1230 ("EDT", "2021-03-20 14:53:01 EDT"),
1231 ];
1232
1233 for (_tz_name, date_str) in us_zones {
1234 new_ucmd!()
1235 .arg("-d")
1236 .arg(date_str)
1237 .arg("+%Y-%m-%d %H:%M:%S")
1238 .succeeds()
1239 .no_stderr();
1240 }
1241 }
1242
1243 #[test]
1244 fn test_date_double_timezone_is_invalid() {
1245 // A date string that specifies a timezone twice is invalid, matching GNU.
1246 // Regression test for issue #12875.
1247 for input in ["EST EST", "EST PST", "2021-03-20 14:53:01 EST EST"] {
1248 new_ucmd!()
1249 .arg("-d")
1250 .arg(input)
1251 .fails_with_code(1)
1252 .stderr_contains("invalid date");
1253 }
1254
1255 // A single trailing timezone abbreviation must still be accepted.
1256 new_ucmd!()
1257 .arg("-d")
1258 .arg("2021-03-20 14:53:01 EST")
1259 .arg("+%Y-%m-%d %H:%M:%S")
1260 .succeeds()
1261 .no_stderr();
1262 }
1263
1264 #[test]
1265 fn test_date_tz_abbreviation_australian_timezones() {
1266 // Test Australian timezone abbreviations (uutils supports, GNU does NOT)
1267 // This demonstrates uutils date going beyond GNU capabilities
1268 let au_zones = vec![
1269 ("AWST", "2021-03-20 14:53:01 AWST"), // Western Australia // spell-checker:disable-line
1270 ("ACST", "2021-03-20 14:53:01 ACST"), // Central Australia (Standard) // spell-checker:disable-line
1271 ("ACDT", "2021-03-20 14:53:01 ACDT"), // Central Australia (Daylight) // spell-checker:disable-line
1272 ("AEST", "2021-03-20 14:53:01 AEST"), // Eastern Australia (Standard)
1273 ("AEDT", "2021-03-20 14:53:01 AEDT"), // Eastern Australia (Daylight)
1274 ];
1275
1276 for (_tz_name, date_str) in au_zones {
1277 new_ucmd!()
1278 .arg("-d")
1279 .arg(date_str)
1280 .arg("+%Y-%m-%d %H:%M:%S")
1281 .succeeds()
1282 .no_stderr();
1283 }
1284 }
1285
1286 #[test]
1287 fn test_date_tz_abbreviation_dst_handling() {
1288 // Test that timezone abbreviations correctly handle DST
1289 // PST is UTC-8, PDT is UTC-7
1290 // March 20, 2021 was during PDT period in Pacific timezone
1291
1292 new_ucmd!()
1293 .arg("-d")
1294 .arg("2021-03-20 14:53:01 PST")
1295 .arg("+%z")
1296 .succeeds()
1297 .no_stderr();
1298
1299 new_ucmd!()
1300 .arg("-d")
1301 .arg("2021-03-20 14:53:01 PDT")
1302 .arg("+%z")
1303 .succeeds()
1304 .no_stderr();
1305 }
1306
1307 #[test]
1308 fn test_date_tz_abbreviation_fixed_offset_outside_season() {
1309 // Abbreviations encode a fixed UTC offset regardless of the date.
1310 // Using a DST abbreviation outside its season should still use the
1311 // fixed offset the abbreviation implies, not the zone's current offset.
1312
1313 // EDT (UTC-4) used in winter (New York observes EST in January)
1314 new_ucmd!()
1315 .env("TZ", "UTC")
1316 .arg("-u")
1317 .arg("-d")
1318 .arg("2026-01-15 10:00 EDT")
1319 .arg("+%F %T %Z")
1320 .succeeds()
1321 .stdout_is("2026-01-15 14:00:00 UTC\n");
1322
1323 // PST (UTC-8) used in summer (Los Angeles observes PDT in June)
1324 new_ucmd!()
1325 .env("TZ", "UTC")
1326 .arg("-u")
1327 .arg("-d")
1328 .arg("2026-06-15 10:00 PST")
1329 .arg("+%F %T %Z")
1330 .succeeds()
1331 .stdout_is("2026-06-15 18:00:00 UTC\n");
1332
1333 // PDT (UTC-7) used in winter
1334 new_ucmd!()
1335 .env("TZ", "UTC")
1336 .arg("-u")
1337 .arg("-d")
1338 .arg("2026-01-15 10:00 PDT")
1339 .arg("+%F %T %Z")
1340 .succeeds()
1341 .stdout_is("2026-01-15 17:00:00 UTC\n");
1342
1343 // CDT (UTC-5) used in winter
1344 new_ucmd!()
1345 .env("TZ", "UTC")
1346 .arg("-u")
1347 .arg("-d")
1348 .arg("2026-01-15 10:00 CDT")
1349 .arg("+%F %T %Z")
1350 .succeeds()
1351 .stdout_is("2026-01-15 15:00:00 UTC\n");
1352
1353 // MDT (UTC-6) used in winter
1354 new_ucmd!()
1355 .env("TZ", "UTC")
1356 .arg("-u")
1357 .arg("-d")
1358 .arg("2026-01-15 10:00 MDT")
1359 .arg("+%F %T %Z")
1360 .succeeds()
1361 .stdout_is("2026-01-15 16:00:00 UTC\n");
1362
1363 // MEST (UTC+2) used in winter
1364 new_ucmd!()
1365 .env("TZ", "UTC")
1366 .arg("-u")
1367 .arg("-d")
1368 .arg("2026-01-15 10:00 MEST")
1369 .arg("+%F %T %Z")
1370 .succeeds()
1371 .stdout_is("2026-01-15 08:00:00 UTC\n");
1372 }
1373
1374 #[test]
1375 fn test_date_tz_abbreviation_with_day_of_week() {
1376 // Test timezone abbreviations with full date format including day of week
1377 new_ucmd!()
1378 .arg("-d")
1379 .arg("Sat 20 Mar 2021 14:53:01 AWST") // spell-checker:disable-line
1380 .arg("+%Y-%m-%d %H:%M:%S")
1381 .succeeds()
1382 .no_stderr();
1383
1384 new_ucmd!()
1385 .arg("-d")
1386 .arg("Sat 20 Mar 2021 14:53:01 EST")
1387 .arg("+%Y-%m-%d %H:%M:%S")
1388 .succeeds()
1389 .no_stderr();
1390 }
1391
1392 #[test]
1393 fn test_date_tz_abbreviation_with_relative_date() {
1394 // Verify that "yesterday" in "-u -d yesterday 10:00 GMT" is resolved
1395 // relative to UTC, not the local TZ.
1396 let expected = new_ucmd!()
1397 .env("TZ", "UTC")
1398 .arg("-u")
1399 .arg("-d")
1400 .arg("yesterday 10:00 GMT")
1401 .arg("+%F %T %Z")
1402 .succeeds()
1403 .stdout_str()
1404 .to_string();
1405 new_ucmd!()
1406 .env("TZ", "Australia/Sydney")
1407 .arg("-u")
1408 .arg("-d")
1409 .arg("yesterday 10:00 GMT")
1410 .arg("+%F %T %Z")
1411 .succeeds()
1412 .stdout_is(expected);
1413 }
1414
1415 #[test]
1416 fn test_date_tz_abbreviation_unknown() {
1417 // Test that unknown timezone abbreviations fall back gracefully
1418 // XYZ is not a valid timezone abbreviation
1419 new_ucmd!()
1420 .arg("-d")
1421 .arg("2021-03-20 14:53:01 XYZ")
1422 .fails()
1423 .stderr_contains("invalid date");
1424 }
1425
1426 #[test]
1427 fn test_date_military_timezone_j_variations() {
1428 // Test multiple variations of 'J' input (case insensitive, with whitespace)
1429 // All should produce midnight (00:00:00)
1430 let test_cases = vec!["J", "j", " J ", " j ", "\tJ\t"];
1431
1432 for input in test_cases {
1433 new_ucmd!()
1434 .env("TZ", "UTC")
1435 .arg("-d")
1436 .arg(input)
1437 .arg("+%T")
1438 .succeeds()
1439 .stdout_is("00:00:00\n");
1440 }
1441
1442 // Test with -u flag to verify UTC behavior
1443 new_ucmd!()
1444 .arg("-u")
1445 .arg("-d")
1446 .arg("J")
1447 .arg("+%T %Z")
1448 .succeeds()
1449 .stdout_contains("00:00:00")
1450 .stdout_contains("UTC");
1451 }
1452
1453 #[test]
1454 fn test_date_military_timezone_j_with_time() {
1455 // 'J' is local time, so "<digits>j" is the time-of-day form (HH or HHMM)
1456 // in the local zone, same as the bare "<digits>" input. GNU accepts it.
1457 let test_cases = vec![
1458 ("8j", "08:00:00"),
1459 ("9j", "09:00:00"),
1460 ("9J", "09:00:00"),
1461 ("12j", "12:00:00"),
1462 ("1230j", "12:30:00"),
1463 ("0j", "00:00:00"),
1464 ("00j", "00:00:00"),
1465 ];
1466
1467 for (input, expected) in test_cases {
1468 new_ucmd!()
1469 .env("TZ", "UTC")
1470 .arg("-d")
1471 .arg(input)
1472 .arg("+%T")
1473 .succeeds()
1474 .stdout_is(format!("{expected}\n"));
1475 }
1476
1477 // Out-of-range times are rejected, same as the bare digit form
1478 for input in ["2400j", "2360j", "12345j"] {
1479 new_ucmd!()
1480 .env("TZ", "UTC")
1481 .arg("-d")
1482 .arg(input)
1483 .fails()
1484 .stderr_contains("invalid date");
1485 }
1486 }
1487
1488 #[test]
1489 fn test_date_empty_string() {
1490 // Empty string should be treated as midnight today
1491 new_ucmd!()
1492 .env("TZ", "UTC+1")
1493 .arg("-d")
1494 .arg("")
1495 .succeeds()
1496 .stdout_contains("00:00:00");
1497 }
1498
1499 #[test]
1500 fn test_date_empty_string_variations() {
1501 // Test multiple variations of empty/whitespace strings
1502 // All should produce midnight (00:00:00)
1503 let test_cases = vec!["", " ", " ", "\t", "\n", " \t ", "\t\n\t", "\x0B", "\x0C"];
1504
1505 for input in test_cases {
1506 new_ucmd!()
1507 .env("TZ", "UTC")
1508 .arg("-d")
1509 .arg(input)
1510 .arg("+%T")
1511 .succeeds()
1512 .stdout_is("00:00:00\n");
1513 }
1514
1515 // Test with -u flag to verify UTC behavior
1516 new_ucmd!()
1517 .arg("-u")
1518 .arg("-d")
1519 .arg("")
1520 .arg("+%T %Z")
1521 .succeeds()
1522 .stdout_contains("00:00:00")
1523 .stdout_contains("UTC");
1524 }
1525
1526 #[test]
1527 fn test_date_whitespace_between_items() {
1528 // GNU date accepts \v and \f as whitespace between items
1529 new_ucmd!()
1530 .env("LANG", "C")
1531 .env("LC_ALL", "C")
1532 .env("TZ", "UTC0")
1533 .args(&["-d", "Jan 23\x0B 2026 1:00AM"])
1534 .succeeds()
1535 .stdout_is("Fri Jan 23 01:00:00 UTC 2026\n");
1536
1537 new_ucmd!()
1538 .env("LANG", "C")
1539 .env("LC_ALL", "C")
1540 .env("TZ", "UTC0")
1541 .args(&["-d", "Jan 23\x0C2026 1:00AM"])
1542 .succeeds()
1543 .stdout_is("Fri Jan 23 01:00:00 UTC 2026\n");
1544 }
1545
1546 #[test]
1547 fn test_date_relative_m9() {
1548 // Military timezone "m9" should be parsed as noon + 9 hours = 21:00 UTC
1549 // When displayed in TZ=UTC+9 (which is UTC-9), this shows as 12:00 local time
1550 new_ucmd!()
1551 .env("TZ", "UTC+9")
1552 .arg("-d")
1553 .arg("m9")
1554 .succeeds()
1555 .stdout_contains("12:00:00");
1556 }
1557
1558 #[test]
1559 fn test_date_military_timezone_with_offset_variations() {
1560 // Test various military timezone + offset combinations
1561 // Format: single letter (a-z except j) optionally followed by 1-2 digits
1562
1563 // Test cases: (input, expected_time_utc)
1564 let test_cases = vec![
1565 ("a", "23:00:00"), // A = UTC+1, midnight in UTC+1 = 23:00 UTC
1566 ("m", "12:00:00"), // M = UTC+12, midnight in UTC+12 = 12:00 UTC
1567 ("z", "00:00:00"), // Z = UTC+0, midnight in UTC+0 = 00:00 UTC
1568 ("m9", "21:00:00"), // M + 9 hours = 12 + 9 = 21:00 UTC
1569 ("a5", "04:00:00"), // A + 5 hours = 23 + 5 = 04:00 UTC (next day)
1570 ("z3", "03:00:00"), // Z + 3 hours = 00 + 3 = 03:00 UTC
1571 ("M", "12:00:00"), // Uppercase should work too
1572 ("A5", "04:00:00"), // Uppercase with offset
1573 ];
1574
1575 for (input, expected) in test_cases {
1576 new_ucmd!()
1577 .env("TZ", "UTC")
1578 .arg("-d")
1579 .arg(input)
1580 .arg("+%T")
1581 .succeeds()
1582 .stdout_is(format!("{expected}\n"));
1583 }
1584 }
1585
1586 #[test]
1587 fn test_date_military_timezone_with_offset_and_date() {
1588 let today = Timestamp::now().to_zoned(TimeZone::UTC).date();
1589
1590 let test_cases = vec![
1591 ("m", -1), // M = UTC+12
1592 ("a", -1), // A = UTC+1
1593 ("n", 0), // N = UTC-1
1594 ("y", 0), // Y = UTC-12
1595 ("z", 0), // Z = UTC
1596 // same day hour offsets
1597 ("n2", 0),
1598 // midnight crossings with hour offsets back to today
1599 ("a1", 0), // exactly to midnight
1600 ("a5", 0), // "overflow" midnight
1601 ("m23", 0),
1602 // midnight crossings with hour offsets to tomorrow
1603 ("n23", 1),
1604 ("y23", 1),
1605 // midnight crossing to yesterday even with positive offset
1606 ("m9", -1), // M = UTC+12 (-12 h + 9h is still `yesterday`)
1607 ];
1608
1609 for (input, day_delta) in test_cases {
1610 let expected_date = today.checked_add(day_delta.days()).unwrap();
1611
1612 let expected = format!("{}\n", expected_date.strftime("%F"));
1613
1614 new_ucmd!()
1615 .env("TZ", "UTC")
1616 .arg("-d")
1617 .arg(input)
1618 .arg("+%F")
1619 .succeeds()
1620 .stdout_is(expected);
1621 }
1622 }
1623
1624 // Locale-aware hour formatting tests
1625 #[test]
1626 #[cfg(unix)]
1627 fn test_date_locale_hour_c_locale() {
1628 // C locale should use 24-hour format
1629 new_ucmd!()
1630 .env("LC_ALL", "C")
1631 .env("TZ", "UTC")
1632 .arg("-d")
1633 .arg("2025-10-11T13:00")
1634 .succeeds()
1635 .stdout_contains("13:00");
1636 }
1637
1638 #[test]
1639 #[cfg(unix)]
1640 fn test_date_locale_hour_en_us() {
1641 // en_US locale typically uses 12-hour format when available
1642 // Note: If locale is not installed on system, falls back to C locale (24-hour)
1643 let result = new_ucmd!()
1644 .env("LC_ALL", "en_US.UTF-8")
1645 .env("TZ", "UTC")
1646 .arg("-d")
1647 .arg("2025-10-11T13:00")
1648 .succeeds();
1649
1650 let stdout = result.stdout_str();
1651 // Accept either 12-hour (if locale available) or 24-hour (if locale unavailable)
1652 // The important part is that the code doesn't crash and handles locale detection gracefully
1653 assert!(
1654 stdout.contains("1:00") || stdout.contains("13:00"),
1655 "date output should contain either 1:00 (12-hour) or 13:00 (24-hour), got: {stdout}"
1656 );
1657 }
1658
1659 #[test]
1660 fn test_date_explicit_format_overrides_locale() {
1661 // Explicit format should override locale preferences
1662 new_ucmd!()
1663 .env("LC_ALL", "en_US.UTF-8")
1664 .env("TZ", "UTC")
1665 .arg("-d")
1666 .arg("2025-10-11T13:00")
1667 .arg("+%H:%M")
1668 .succeeds()
1669 .stdout_is("13:00\n");
1670 }
1671
1672 // Comprehensive locale formatting tests to verify actual locale format strings are used
1673 #[test]
1674 #[cfg(unix)]
1675 fn test_date_locale_leading_zeros_en_us() {
1676 // Test for leading zeros in en_US locale
1677 // en_US uses %I (01-12) with leading zeros, not %l (1-12) without
1678 let result = new_ucmd!()
1679 .env("LC_ALL", "en_US.UTF-8")
1680 .env("TZ", "UTC")
1681 .arg("-d")
1682 .arg("2025-12-14T01:00")
1683 .succeeds();
1684
1685 let stdout = result.stdout_str();
1686 // If locale is available, should have leading zero: "01:00"
1687 // If locale unavailable (falls back to C), may have "01:00" (24-hour) or " 1:00"
1688 // Key point: output should match what nl_langinfo(D_T_FMT) specifies
1689 if stdout.contains("AM") || stdout.contains("PM") {
1690 // 12-hour format detected - should have leading zero in en_US
1691 assert!(
1692 stdout.contains("01:00") || stdout.contains(" 1:00"),
1693 "en_US 12-hour format should show '01:00 AM' or ' 1:00 AM', got: {stdout}"
1694 );
1695 }
1696 }
1697
1698 #[test]
1699 #[cfg(unix)]
1700 fn test_date_locale_c_uses_24_hour() {
1701 // C/POSIX locale must use 24-hour format
1702 let result = new_ucmd!()
1703 .env("LC_ALL", "C")
1704 .env("TZ", "UTC")
1705 .arg("-d")
1706 .arg("2025-12-14T13:00")
1707 .succeeds();
1708
1709 let stdout = result.stdout_str();
1710 // C locale uses 24-hour format, no AM/PM
1711 assert!(
1712 !stdout.contains("AM") && !stdout.contains("PM"),
1713 "C locale should not use AM/PM, got: {stdout}"
1714 );
1715 assert!(
1716 stdout.contains("13"),
1717 "C locale should show 13 (24-hour), got: {stdout}"
1718 );
1719 }
1720
1721 #[test]
1722 #[cfg(unix)]
1723 fn test_date_locale_timezone_included() {
1724 // Verify timezone is included in output (implementation adds %Z if missing)
1725 let result = new_ucmd!()
1726 .env("LC_ALL", "C")
1727 .env("TZ", "UTC")
1728 .arg("-d")
1729 .arg("2025-12-14T13:00")
1730 .succeeds();
1731
1732 let stdout = result.stdout_str();
1733 assert!(
1734 stdout.contains("UTC") || stdout.contains("+00"),
1735 "Output should contain timezone information, got: {stdout}"
1736 );
1737 }
1738
1739 #[test]
1740 #[cfg(unix)]
1741 fn test_date_locale_format_structure() {
1742 // Test that output follows locale-defined structure (not hardcoded)
1743 let result = new_ucmd!()
1744 .env("LC_ALL", "C")
1745 .env("TZ", "UTC")
1746 .arg("-d")
1747 .arg("2025-12-14T13:00:00")
1748 .succeeds();
1749
1750 let stdout = result.stdout_str();
1751
1752 // Should contain weekday abbreviation
1753 let weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
1754 assert!(
1755 weekdays.iter().any(|day| stdout.contains(day)),
1756 "Output should contain weekday, got: {stdout}"
1757 );
1758
1759 // Should contain month
1760 let months = [
1761 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
1762 ];
1763 assert!(
1764 months.iter().any(|month| stdout.contains(month)),
1765 "Output should contain month, got: {stdout}"
1766 );
1767
1768 // Should contain year
1769 assert!(
1770 stdout.contains("2025"),
1771 "Output should contain year, got: {stdout}"
1772 );
1773 }
1774
1775 #[test]
1776 #[cfg(unix)]
1777 fn test_date_locale_format_not_hardcoded() {
1778 // This test verifies we're not using hardcoded format strings
1779 // by checking that the format actually comes from the locale system
1780
1781 // Test with C locale
1782 let c_result = new_ucmd!()
1783 .env("LC_ALL", "C")
1784 .env("TZ", "UTC")
1785 .arg("-d")
1786 .arg("2025-12-14T01:00:00")
1787 .succeeds();
1788
1789 let c_output = c_result.stdout_str();
1790
1791 // C locale should use 24-hour format
1792 assert!(
1793 c_output.contains("01:00") || c_output.contains(" 1:00"),
1794 "C locale output: {c_output}"
1795 );
1796 assert!(
1797 !c_output.contains("AM") && !c_output.contains("PM"),
1798 "C locale should not have AM/PM: {c_output}"
1799 );
1800 }
1801
1802 #[test]
1803 #[cfg(unix)]
1804 fn test_date_locale_en_us_vs_c_difference() {
1805 // Verify that en_US and C locales produce different outputs
1806 // (if en_US locale is available on the system)
1807
1808 let c_result = new_ucmd!()
1809 .env("LC_ALL", "C")
1810 .env("TZ", "UTC")
1811 .arg("-d")
1812 .arg("2025-12-14T13:00:00")
1813 .succeeds();
1814
1815 let en_us_result = new_ucmd!()
1816 .env("LC_ALL", "en_US.UTF-8")
1817 .env("TZ", "UTC")
1818 .arg("-d")
1819 .arg("2025-12-14T13:00:00")
1820 .succeeds();
1821
1822 let c_output = c_result.stdout_str();
1823 let en_us_output = en_us_result.stdout_str();
1824
1825 // C locale: 24-hour, no AM/PM
1826 assert!(
1827 !c_output.contains("AM") && !c_output.contains("PM"),
1828 "C locale should not have AM/PM: {c_output}"
1829 );
1830
1831 // en_US: If locale is installed, should have AM/PM (12-hour)
1832 // If not installed, falls back to C locale
1833 if en_us_output.contains("PM") {
1834 // Locale is available and using 12-hour format
1835 assert!(
1836 en_us_output.contains("1:00") || en_us_output.contains("01:00"),
1837 "en_US with 12-hour should show 1:00 PM or 01:00 PM, got: {en_us_output}"
1838 );
1839 }
1840 }
1841
1842 #[test]
1843 #[cfg(unix)]
1844 fn test_date_locale_hu_hungarian() {
1845 // Regression test for uutils/coreutils#11240: the GNU modifier fast-path
1846 // ("%-e") used to run before ICU localization, so "%b"/"%A" came out in
1847 // English even under hu_HU.UTF-8. Pin an explicit format string so the
1848 // assertion is deterministic across glibc versions (the default D_T_FMT
1849 // for hu_HU differs between distros).
1850 if !is_locale_available("hu_HU.UTF-8") {
1851 return;
1852 }
1853
1854 let result = new_ucmd!()
1855 .env("LC_ALL", "hu_HU.UTF-8")
1856 .env("TZ", "UTC")
1857 .arg("-d")
1858 .arg("2025-12-14T13:00:00")
1859 .arg("+%Y. %b %-e., %A, %H:%M:%S %Z")
1860 .succeeds();
1861
1862 assert_eq!(
1863 result.stdout_str(),
1864 "2025. dec 14., vasárnap, 13:00:00 UTC\n"
1865 );
1866 }
1867
1868 #[test]
1869 #[cfg(any(target_vendor = "apple", target_os = "linux", target_os = "android"))]
1870 fn test_date_locale_fr_french() {
1871 // Test French locale (fr_FR.UTF-8) behavior
1872 // French typically uses 24-hour format and may have localized day/month names
1873
1874 let result = new_ucmd!()
1875 .env("LC_ALL", "fr_FR.UTF-8")
1876 .env("TZ", "UTC")
1877 .arg("-d")
1878 .arg("2025-12-14T13:00:00")
1879 .succeeds();
1880
1881 let stdout = result.stdout_str();
1882
1883 // French locale should use 24-hour format (no AM/PM)
1884 assert!(
1885 !stdout.contains("AM") && !stdout.contains("PM"),
1886 "French locale should use 24-hour format (no AM/PM), got: {stdout}"
1887 );
1888
1889 // Should have 13:00 (not 1:00)
1890 assert!(
1891 stdout.contains("13:00"),
1892 "French locale should show 13:00 for 1 PM, got: {stdout}"
1893 );
1894
1895 // Timezone should be included (our implementation adds %Z if missing)
1896 assert!(
1897 stdout.contains("UTC") || stdout.contains("+00") || stdout.contains('Z'),
1898 "Output should include timezone information, got: {stdout}"
1899 );
1900 }
1901
1902 #[test]
1903 fn test_date_posix_format_specifiers() {
1904 let cases = [
1905 // %r: 12-hour time with zero-padded hour (08:17:48 AM, not 8:17:48 AM)
1906 ("%r", "08:17:48 AM"),
1907 // %x: locale date in MM/DD/YY format
1908 ("%x", "01/19/97"),
1909 // %X: locale time in HH:MM:SS format
1910 ("%X", "08:17:48"),
1911 // %:8z: invalid format (width between : and z) should output literally (lenient mode)
1912 ("%:8z", "%:8z"),
1913 ];
1914
1915 for (format, expected) in cases {
1916 new_ucmd!()
1917 .env("TZ", "UTC")
1918 .arg("-d")
1919 .arg("1997-01-19 08:17:48")
1920 .arg(format!("+{format}"))
1921 .succeeds()
1922 .stdout_is(format!("{expected}\n"));
1923 }
1924 }
1925
1926 #[test]
1927 #[cfg(any(target_vendor = "apple", target_os = "linux"))]
1928 fn test_date_format_b_french_locale() {
1929 // Test both %B and %b formats with French locale using a loop
1930 // This test expects localized month names when i18n support is available
1931 let test_cases = [
1932 ("2025-01-15", "janvier", "janv."), // Wednesday = mercredi, mer.
1933 ("2025-02-15", "février", "févr."), // Saturday = samedi, sam.
1934 ];
1935
1936 for (date, expected_full, expected_abbrev) in &test_cases {
1937 let result = new_ucmd!()
1938 .env("LC_TIME", "fr_FR.UTF-8")
1939 .env("TZ", "UTC")
1940 .arg("-d")
1941 .arg(date)
1942 .arg("+%B %b")
1943 .succeeds();
1944
1945 let output = result.stdout_str().trim();
1946 let expected = format!("{expected_full} {expected_abbrev}");
1947
1948 if output == expected {
1949 // i18n feature is working - test passed
1950 assert_eq!(output, expected);
1951 } else {
1952 // i18n feature not available, skip test
1953 println!(
1954 "Skipping French locale test for {date} - i18n feature not available, got: {output}"
1955 );
1956 return; // Exit early if i18n not available
1957 }
1958 }
1959 }
1960
1961 #[test]
1962 #[cfg(any(target_vendor = "apple", target_os = "linux"))]
1963 fn test_date_format_a_french_locale() {
1964 // Test both %A and %a formats with French locale using a loop
1965 // This test expects localized day names when i18n support is available
1966 let test_cases = [
1967 ("2025-01-15", "mercredi", "mer."), // Wednesday
1968 ("2025-02-15", "samedi", "sam."), // Saturday
1969 ];
1970
1971 for (date, expected_full, expected_abbrev) in &test_cases {
1972 let result = new_ucmd!()
1973 .env("LC_TIME", "fr_FR.UTF-8")
1974 .env("TZ", "UTC")
1975 .arg("-d")
1976 .arg(date)
1977 .arg("+%A %a")
1978 .succeeds();
1979
1980 let output = result.stdout_str().trim();
1981 let expected = format!("{expected_full} {expected_abbrev}");
1982
1983 if output == expected {
1984 // i18n feature is working - test passed
1985 assert_eq!(output, expected);
1986 } else {
1987 // i18n feature not available, skip test
1988 println!(
1989 "Skipping French day locale test for {date} - i18n feature not available, got: {output}"
1990 );
1991 return; // Exit early if i18n not available
1992 }
1993 }
1994 }
1995
1996 #[test]
1997 #[cfg(any(target_vendor = "apple", target_os = "linux"))]
1998 fn test_date_french_full_sentence() {
1999 let result = new_ucmd!()
2000 .env("LANG", "fr_FR.UTF-8")
2001 .env("TZ", "UTC")
2002 .arg("-d")
2003 .arg("2026-01-21")
2004 .arg("+Nous sommes le %A %d %B %Y")
2005 .succeeds();
2006
2007 let output = result.stdout_str().trim();
2008 let expected = "Nous sommes le mercredi 21 janvier 2026";
2009
2010 if output == expected {
2011 // i18n feature is working - test passed
2012 assert_eq!(output, expected);
2013 } else {
2014 // i18n feature not available, skip test
2015 println!("Skipping French full sentence test - i18n feature not available, got: {output}");
2016 }
2017 }
2018
2019 /// Test that %x format specifier respects locale settings
2020 /// This is a regression test for locale-aware date formatting
2021 #[test]
2022 #[ignore = "https://bugs.launchpad.net/ubuntu/+source/rust-coreutils/+bug/2137410"]
2023 #[cfg(any(target_vendor = "apple", target_os = "linux"))]
2024 fn test_date_format_x_locale_aware() {
2025 // With C locale, %x should output MM/DD/YY (US format)
2026 new_ucmd!()
2027 .env("TZ", "UTC")
2028 .env("LC_ALL", "C")
2029 .arg("-d")
2030 .arg("1997-01-19 08:17:48")
2031 .arg("+%x")
2032 .succeeds()
2033 .stdout_is("01/19/97\n");
2034
2035 // With French locale, %x should output DD/MM/YYYY (European format)
2036 // GNU date outputs: 19/01/1997
2037 new_ucmd!()
2038 .env("TZ", "UTC")
2039 .env("LC_ALL", "fr_FR.UTF-8")
2040 .arg("-d")
2041 .arg("1997-01-19 08:17:48")
2042 .arg("+%x")
2043 .succeeds()
2044 .stdout_is("19/01/1997\n");
2045 }
2046
2047 #[test]
2048 fn test_date_parenthesis_comment() {
2049 // GNU compatibility: Text in parentheses is treated as a comment and removed.
2050 let cases = [
2051 // (input, format, expected_output)
2052 ("(", "+%H:%M:%S", "00:00:00\n"),
2053 ("1(ignore comment to eol", "+%H:%M:%S", "01:00:00\n"),
2054 ("2026-01-05(this is a comment", "+%Y-%m-%d", "2026-01-05\n"),
2055 ("2026(this is a comment)-01-05", "+%Y-%m-%d", "2026-01-05\n"),
2056 ("((foo)2026-01-05)", "+%H:%M:%S", "00:00:00\n"), // Nested/unbalanced case
2057 ("(2026-01-05(foo))", "+%H:%M:%S", "00:00:00\n"), // Balanced parentheses removed (empty result)
2058 ];
2059
2060 for (input, format, expected) in cases {
2061 new_ucmd!()
2062 .env("TZ", "UTC")
2063 .arg("-d")
2064 .arg(input)
2065 .arg("-u")
2066 .arg(format)
2067 .succeeds()
2068 .stdout_only(expected);
2069 }
2070 }
2071
2072 #[test]
2073 fn test_date_strftime_narrow_width_on_wide_default() {
2074 // `%j` has a default width of 3. Requesting `%02j` on day 1 should yield `01`.
2075 // uutils currently yields `1`.
2076 new_ucmd!()
2077 .env("LC_ALL", "C")
2078 .env("TZ", "UTC")
2079 .arg("-d")
2080 .arg("2024-01-01")
2081 .arg("+%02j")
2082 .succeeds()
2083 .stdout_is("01\n");
2084 }
2085
2086 #[test]
2087 fn test_date_negative_fractional_epoch_flooring() {
2088 // GNU date floors `%s` toward negative infinity for negative fractional
2089 // epochs, while jiff truncates toward zero. See parse_datetime issue #283.
2090 for (input, format, expected) in [
2091 ("@-1.5", "+%s", "-2\n"),
2092 ("@-0.25", "+%s", "-1\n"),
2093 ("@-2.75", "+%s.%N", "-3.250000000\n"),
2094 ("@-100.5", "+%s", "-101\n"),
2095 // Positive fractions and whole seconds are unaffected.
2096 ("@42.9", "+%s", "42\n"),
2097 ("@-7", "+%s", "-7\n"),
2098 // `%%s` stays a literal specifier and must not be substituted.
2099 ("@-1.5", "+%%s=%s", "%s=-2\n"),
2100 ] {
2101 new_ucmd!()
2102 .env("LC_ALL", "C")
2103 .env("TZ", "UTC")
2104 .arg("-d")
2105 .arg(input)
2106 .arg(format)
2107 .succeeds()
2108 .stdout_is(expected);
2109 }
2110 }
2111
2112 #[test]
2113 fn test_date_input_hhmm_ampm() {
2114 // GNU date accepts a 12-hour meridiem suffix on a combined date+time.
2115 // Regression test for https://github.com/uutils/parse_datetime/issues/282.
2116 for (input, expected) in [
2117 ("2024-06-15 12:00 PM", "12:00\n"),
2118 ("2024-06-15 11:30am", "11:30\n"),
2119 ("2024-06-15 3:00 PM", "15:00\n"),
2120 ("2024-06-15 12:00 AM", "00:00\n"),
2121 ("2024-06-15 3:00 p.m.", "15:00\n"),
2122 ] {
2123 new_ucmd!()
2124 .env("LC_ALL", "C")
2125 .env("TZ", "UTC")
2126 .arg("-d")
2127 .arg(input)
2128 .arg("+%H:%M")
2129 .succeeds()
2130 .stdout_is(expected);
2131 }
2132 }
2133
2134 #[test]
2135 fn test_date_input_trailing_tz_abbrev_rezones() {
2136 // `TZ=UTC+1 date -d '2024-01-01 EST'` should display the instant in UTC+1
2137 // (GNU: 04:00:00 -01:00), not leave it in EST (the pre-fix uutils
2138 // behavior was 00:00:00 -05). The trailing abbreviation only specifies
2139 // the input timezone; output should be re-zoned to local.
2140 // Regression test for https://github.com/uutils/parse_datetime/issues/281.
2141 new_ucmd!()
2142 .env("LC_ALL", "C")
2143 .env("TZ", "UTC+1")
2144 .arg("-d")
2145 .arg("2024-01-01 EST")
2146 .arg("+%H:%M:%S %:z")
2147 .succeeds()
2148 .stdout_is("04:00:00 -01:00\n");
2149 }
2150
2151 #[test]
2152 fn test_date_strftime_case_flag_on_alt_ampm() {
2153 // `%P` is GNU's lowercase am/pm. `%#P` should stay lowercase in GNU; uutils flips to `PM`.
2154 new_ucmd!()
2155 .env("LC_ALL", "C")
2156 .env("TZ", "UTC")
2157 .arg("-d")
2158 .arg("2024-06-15 13:45:30")
2159 .arg("+%#P")
2160 .succeeds()
2161 .stdout_is("pm\n");
2162 }
2163
2164 #[test]
2165 #[ignore = "https://github.com/uutils/coreutils/issues/11658 — GNU date applies flags/widths to `%N` (nanoseconds); uutils ignores/mishandles them."]
2166 fn test_date_strftime_n_width_and_flags() {
2167 // `%_3N` should space-pad nanoseconds to width 3. GNU outputs `0 `; uutils outputs `0`.
2168 new_ucmd!()
2169 .env("LC_ALL", "C")
2170 .env("TZ", "UTC")
2171 .arg("-d")
2172 .arg("@0")
2173 .arg("+%_3N")
2174 .succeeds()
2175 .stdout_is("0 \n");
2176 // `%-N` (no-padding flag) should still output the full 9-digit default.
2177 // GNU: `000000000`; uutils: `0`.
2178 new_ucmd!()
2179 .env("LC_ALL", "C")
2180 .env("TZ", "UTC")
2181 .arg("-d")
2182 .arg("@0")
2183 .arg("+%-N")
2184 .succeeds()
2185 .stdout_is("000000000\n");
2186 }
2187
2188 #[test]
2189 #[ignore = "https://github.com/uutils/coreutils/issues/11657 — GNU date treats composite strftime specifiers (%D, %F, %T, ...) as atomic; flags like `-` should not propagate to sub-fields."]
2190 fn test_date_strftime_flag_on_composite() {
2191 // GNU `%-D` keeps `06/15/24` (flag ignored on composite).
2192 // uutils applies `-` to inner `%m`, producing `6/15/24`.
2193 new_ucmd!()
2194 .env("LC_ALL", "C")
2195 .env("TZ", "UTC")
2196 .arg("-d")
2197 .arg("2024-06-15")
2198 .arg("+%-D")
2199 .succeeds()
2200 .stdout_is("06/15/24\n");
2201 }
2202
2203 #[test]
2204 fn test_date_strftime_o_modifier() {
2205 // In C locale the `O` modifier is a no-op (alternative numeric symbols).
2206 // GNU renders `%Om` as `06` for June; uutils renders it as the literal `%Om`.
2207 new_ucmd!()
2208 .env("LC_ALL", "C")
2209 .env("TZ", "UTC")
2210 .arg("-d")
2211 .arg("2024-06-15")
2212 .arg("+%Om-%Oy-%Od")
2213 .succeeds()
2214 .stdout_is("06-24-15\n");
2215 }
2216
2217 #[test]
2218 #[ignore = "https://github.com/uutils/parse_datetime/issues/280 — GNU date accepts bare timezone abbreviations (UT, GMT, ...) meaning `now in that TZ`; parse_datetime rejects them."]
2219 fn test_date_bare_timezone_abbreviation() {
2220 // GNU: `date -d ut`, `date -d UT`, `date -d gmt` → current time in UTC.
2221 // uutils: "invalid date" error.
2222 for input in ["ut", "UT", "gmt", "GMT"] {
2223 new_ucmd!()
2224 .env("TZ", "UTC+1")
2225 .arg("-d")
2226 .arg(input)
2227 .arg("+%Z")
2228 .succeeds()
2229 .stdout_is("UTC\n");
2230 }
2231 }
2232
2233 #[test]
2234 #[ignore = "https://github.com/uutils/parse_datetime/issues/279. GNU date silently ignores unrecognized trailing tokens (e.g. `8 j`), but parse_datetime rejects them."]
2235 fn test_date_ignores_unrecognized_trailing_tokens() {
2236 // GNU compatibility: trailing unknown word-tokens after a valid number are ignored.
2237 // GNU parses `8 j` (number, space, token) as hour 8; our parse_datetime crate errors out.
2238 // The no-space `8j` form is handled directly (see test_date_military_timezone_j_with_time).
2239 new_ucmd!()
2240 .env("TZ", "UTC")
2241 .arg("-u")
2242 .arg("-d")
2243 .arg("8 j")
2244 .arg("+%H:%M:%S")
2245 .succeeds()
2246 .stdout_only("08:00:00\n");
2247 }
2248
2249 #[test]
2250 fn test_date_parenthesis_vs_other_special_chars() {
2251 // Ensure parentheses are special but other chars like [, ., ^ are still rejected
2252 for special_char in ["[", ".", "^"] {
2253 new_ucmd!()
2254 .arg("-d")
2255 .arg(special_char)
2256 .fails()
2257 .stderr_contains("invalid date");
2258 }
2259 }
2260
2261 #[test]
2262 #[cfg(unix)]
2263 fn test_date_iranian_locale_solar_hijri_calendar() {
2264 // Test Iranian locale uses Solar Hijri calendar
2265 // Verify the Solar Hijri calendar is used in the Iranian locale
2266 if !is_locale_available("fa_IR.UTF-8") {
2267 println!("Skipping Iranian locale test - fa_IR.UTF-8 locale not available");
2268 return;
2269 }
2270
2271 // Get current year in Gregorian calendar
2272 let current_year: i32 = new_ucmd!()
2273 .env("LC_ALL", "C")
2274 .arg("+%Y")
2275 .succeeds()
2276 .stdout_str()
2277 .trim()
2278 .parse()
2279 .unwrap();
2280
2281 // 03-19 and 03-22 of the same Gregorian year are in different years in the
2282 // Solar Hijri calendar
2283 let year_march_19: i32 = new_ucmd!()
2284 .env("LC_ALL", "fa_IR.UTF-8")
2285 .arg("-d")
2286 .arg(format!("{current_year}-03-19"))
2287 .arg("+%Y")
2288 .succeeds()
2289 .stdout_str()
2290 .trim()
2291 .parse()
2292 .unwrap();
2293
2294 let year_march_22: i32 = new_ucmd!()
2295 .env("LC_ALL", "fa_IR.UTF-8")
2296 .arg("-d")
2297 .arg(format!("{current_year}-03-22"))
2298 .arg("+%Y")
2299 .succeeds()
2300 .stdout_str()
2301 .trim()
2302 .parse()
2303 .unwrap();
2304
2305 // Years should differ by 1
2306 assert_eq!(year_march_19, year_march_22 - 1);
2307
2308 // The difference between the Gregorian year is 621 or 622 years
2309 assert_eq!(year_march_19, current_year - 622);
2310 assert_eq!(year_march_22, current_year - 621);
2311
2312 // Check that --iso-8601 and --rfc-3339 use the Gregorian calendar
2313 let iso_result = new_ucmd!()
2314 .env("LC_ALL", "fa_IR.UTF-8")
2315 .arg("--iso-8601=hours")
2316 .succeeds();
2317 let iso_output = iso_result.stdout_str();
2318 assert!(iso_output.starts_with(&current_year.to_string()));
2319
2320 let rfc_result = new_ucmd!()
2321 .env("LC_ALL", "fa_IR.UTF-8")
2322 .arg("--rfc-3339=date")
2323 .succeeds();
2324 let rfc_output = rfc_result.stdout_str();
2325 assert!(rfc_output.starts_with(&current_year.to_string()));
2326 }
2327
2328 #[test]
2329 #[cfg(unix)]
2330 fn test_date_ethiopian_locale_calendar() {
2331 // Test Ethiopian locale uses Ethiopian calendar
2332 // Verify the Ethiopian calendar is used in the Ethiopian locale
2333 if !is_locale_available("am_ET.UTF-8") {
2334 println!("Skipping Ethiopian locale test - am_ET.UTF-8 locale not available");
2335 return;
2336 }
2337
2338 // Get current year in Gregorian calendar
2339 let current_year: i32 = new_ucmd!()
2340 .env("LC_ALL", "C")
2341 .arg("+%Y")
2342 .succeeds()
2343 .stdout_str()
2344 .trim()
2345 .parse()
2346 .unwrap();
2347
2348 // 09-10 and 09-12 of the same Gregorian year are in different years in the
2349 // Ethiopian calendar
2350 let year_september_10: i32 = new_ucmd!()
2351 .env("LC_ALL", "am_ET.UTF-8")
2352 .arg("-d")
2353 .arg(format!("{current_year}-09-10"))
2354 .arg("+%Y")
2355 .succeeds()
2356 .stdout_str()
2357 .trim()
2358 .parse()
2359 .unwrap();
2360
2361 let year_september_12: i32 = new_ucmd!()
2362 .env("LC_ALL", "am_ET.UTF-8")
2363 .arg("-d")
2364 .arg(format!("{current_year}-09-12"))
2365 .arg("+%Y")
2366 .succeeds()
2367 .stdout_str()
2368 .trim()
2369 .parse()
2370 .unwrap();
2371
2372 // Years should differ by 1
2373 assert_eq!(year_september_10, year_september_12 - 1);
2374
2375 // The difference between the Gregorian year is 7 or 8 years
2376 assert_eq!(year_september_10, current_year - 8);
2377 assert_eq!(year_september_12, current_year - 7);
2378
2379 // Check that --iso-8601 and --rfc-3339 use the Gregorian calendar
2380 let iso_result = new_ucmd!()
2381 .env("LC_ALL", "am_ET.UTF-8")
2382 .arg("--iso-8601=hours")
2383 .succeeds();
2384 let iso_output = iso_result.stdout_str();
2385 assert!(iso_output.starts_with(&current_year.to_string()));
2386
2387 let rfc_result = new_ucmd!()
2388 .env("LC_ALL", "am_ET.UTF-8")
2389 .arg("--rfc-3339=date")
2390 .succeeds();
2391 let rfc_output = rfc_result.stdout_str();
2392 assert!(rfc_output.starts_with(&current_year.to_string()));
2393 }
2394
2395 #[test]
2396 #[cfg(unix)]
2397 fn test_date_thai_locale_solar_calendar() {
2398 // Test Thai locale uses Thai solar calendar
2399 // Verify the Thai solar calendar is used with the Thai locale
2400 if !is_locale_available("th_TH.UTF-8") {
2401 println!("Skipping Thai locale test - th_TH.UTF-8 locale not available");
2402 return;
2403 }
2404
2405 // Get current year in Gregorian calendar
2406 let current_year: i32 = new_ucmd!()
2407 .env("LC_ALL", "C")
2408 .arg("+%Y")
2409 .succeeds()
2410 .stdout_str()
2411 .trim()
2412 .parse()
2413 .unwrap();
2414
2415 // Since 1941, the year in the Thai solar calendar is the Gregorian year plus 543
2416 let thai_year: i32 = new_ucmd!()
2417 .env("LC_ALL", "th_TH.UTF-8")
2418 .arg("+%Y")
2419 .succeeds()
2420 .stdout_str()
2421 .trim()
2422 .parse()
2423 .unwrap();
2424
2425 assert_eq!(thai_year, current_year + 543);
2426
2427 // All months that have 31 days have names that end with "คม" (Thai characters)
2428 let days_31_suffix = "\u{0E04}\u{0E21}"; // "คม" in Unicode
2429
2430 for month in ["01", "03", "05", "07", "08", "10", "12"] {
2431 let month_result = new_ucmd!()
2432 .env("LC_ALL", "th_TH.UTF-8")
2433 .arg("--date")
2434 .arg(format!("{current_year}-{month}-01"))
2435 .arg("+%B")
2436 .succeeds();
2437 let month_name = month_result.stdout_str();
2438
2439 assert!(
2440 month_name.trim().ends_with(days_31_suffix),
2441 "Month {month} should end with 'คม', got: {month_name}"
2442 );
2443 }
2444
2445 // Check that --iso-8601 and --rfc-3339 use the Gregorian calendar
2446 let iso_result = new_ucmd!()
2447 .env("LC_ALL", "th_TH.UTF-8")
2448 .arg("--iso-8601=hours")
2449 .succeeds();
2450 let iso_output = iso_result.stdout_str();
2451 assert!(iso_output.starts_with(&current_year.to_string()));
2452
2453 let rfc_result = new_ucmd!()
2454 .env("LC_ALL", "th_TH.UTF-8")
2455 .arg("--rfc-3339=date")
2456 .succeeds();
2457 let rfc_output = rfc_result.stdout_str();
2458 assert!(rfc_output.starts_with(&current_year.to_string()));
2459 }
2460
2461 #[cfg(unix)]
2462 fn check_date(locale: &str, date: &str, fmt: &str, expected: &str) {
2463 let actual = new_ucmd!()
2464 .env("LC_ALL", locale)
2465 .arg("-d")
2466 .arg(date)
2467 .arg(fmt)
2468 .succeeds()
2469 .stdout_str()
2470 .trim()
2471 .to_string();
2472 assert_eq!(actual, expected, "LC_ALL={locale} date -d '{date}' '{fmt}'");
2473 }
2474
2475 #[test]
2476 #[cfg(unix)]
2477 fn test_locale_calendar_conversions() {
2478 // Persian (Solar Hijri) - Nowruz is March 20/21
2479 for (d, e) in [
2480 ("2026-01-01", "1404-10-11"),
2481 ("2026-01-26", "1404-11-06"),
2482 ("2026-03-20", "1404-12-29"),
2483 ("2026-03-21", "1405-01-01"),
2484 ("2026-03-22", "1405-01-02"),
2485 ("2026-06-15", "1405-03-25"),
2486 ("2026-12-31", "1405-10-10"),
2487 ("2025-03-20", "1403-12-30"),
2488 ("2025-03-21", "1404-01-01"),
2489 ("2024-03-19", "1402-12-29"),
2490 ("2024-03-20", "1403-01-01"),
2491 ("2000-03-20", "1379-01-01"),
2492 ] {
2493 check_date("fa_IR.UTF-8", d, "+%Y-%m-%d", e);
2494 }
2495
2496 // Thai Buddhist (year + 543, same month/day)
2497 for (d, e) in [
2498 ("2026-01-01", "2569-01-01"),
2499 ("2026-01-26", "2569-01-26"),
2500 ("2026-06-15", "2569-06-15"),
2501 ("2026-12-31", "2569-12-31"),
2502 ("2025-01-01", "2568-01-01"),
2503 ("2024-02-29", "2567-02-29"),
2504 ("2000-01-01", "2543-01-01"),
2505 ("1970-01-01", "2513-01-01"),
2506 ] {
2507 check_date("th_TH.UTF-8", d, "+%Y-%m-%d", e);
2508 }
2509
2510 // Ethiopian (13 months, New Year on Sept 11)
2511 for (d, e) in [
2512 ("2026-01-01", "2018-04-23"),
2513 ("2026-01-26", "2018-05-18"),
2514 ("2026-09-10", "2018-13-05"),
2515 ("2026-09-11", "2019-01-01"),
2516 ("2026-09-12", "2019-01-02"),
2517 ("2026-12-31", "2019-04-22"),
2518 ("2025-09-11", "2018-01-01"),
2519 ("2025-09-10", "2017-13-05"),
2520 ("2000-09-11", "1993-01-01"),
2521 ] {
2522 check_date("am_ET.UTF-8", d, "+%Y-%m-%d", e);
2523 }
2524 }
2525
2526 #[test]
2527 #[cfg(unix)]
2528 fn test_locale_month_names() {
2529 // %B full month names: Jan, Jun, Dec for each locale
2530 for (loc, jan, jun, dec) in [
2531 ("fr_FR.UTF-8", "janvier", "juin", "décembre"),
2532 ("de_DE.UTF-8", "Januar", "Juni", "Dezember"),
2533 ("es_ES.UTF-8", "enero", "junio", "diciembre"),
2534 ("it_IT.UTF-8", "gennaio", "giugno", "dicembre"),
2535 ("pt_BR.UTF-8", "janeiro", "junho", "dezembro"),
2536 ("hu_HU.UTF-8", "január", "június", "december"),
2537 ("ja_JP.UTF-8", "1月", "6月", "12月"),
2538 ("zh_CN.UTF-8", "一月", "六月", "十二月"),
2539 ] {
2540 check_date(loc, "2026-01-15", "+%B", jan);
2541 check_date(loc, "2026-06-15", "+%B", jun);
2542 check_date(loc, "2026-12-15", "+%B", dec);
2543 }
2544 }
2545
2546 #[test]
2547 #[cfg(unix)]
2548 fn test_locale_abbreviated_month_names() {
2549 // %b abbreviated month names: Feb, Jun, Dec for each locale
2550 // This test ensures we don't get double periods in locales like Hungarian
2551 // where ICU returns "febr." but the format string also adds a period after %b
2552 for (loc, feb, jun, dec) in [
2553 ("fr_FR.UTF-8", "févr", "juin", "déc"),
2554 ("de_DE.UTF-8", "Feb", "Jun", "Dez"),
2555 ("es_ES.UTF-8", "feb", "jun", "dic"),
2556 ("it_IT.UTF-8", "feb", "giu", "dic"),
2557 ("pt_BR.UTF-8", "fev", "jun", "dez"),
2558 ("ja_JP.UTF-8", "2月", "6月", "12月"),
2559 ("zh_CN.UTF-8", "2月", "6月", "12月"),
2560 // Hungarian locale - the fix ensures no double periods
2561 ("hu_HU.UTF-8", "febr", "jún", "dec"),
2562 ] {
2563 check_date(loc, "2026-02-12", "+%b", feb);
2564 check_date(loc, "2026-06-14", "+%b", jun);
2565 check_date(loc, "2026-12-09", "+%b", dec);
2566 }
2567 }
2568
2569 #[test]
2570 #[cfg(unix)]
2571 fn test_locale_day_names() {
2572 // %A full day names: Mon (26th), Sun (25th), Sat (24th) Jan 2026
2573 for (loc, mon, sun, sat) in [
2574 ("fr_FR.UTF-8", "lundi", "dimanche", "samedi"),
2575 ("de_DE.UTF-8", "Montag", "Sonntag", "Samstag"),
2576 ("es_ES.UTF-8", "lunes", "domingo", "sábado"),
2577 ("ja_JP.UTF-8", "月曜日", "日曜日", "土曜日"),
2578 ("zh_CN.UTF-8", "星期一", "星期日", "星期六"),
2579 ] {
2580 check_date(loc, "2026-01-26", "+%A", mon);
2581 check_date(loc, "2026-01-25", "+%A", sun);
2582 check_date(loc, "2026-01-24", "+%A", sat);
2583 }
2584 }
2585
2586 #[test]
2587 fn test_percent_percent_not_replaced() {
2588 let cases = [
2589 // Time conversion specifiers
2590 (
2591 "+%%H%%I%%k%%l%%M%%N%%p%%P%%r%%R%%s%%S%%T%%X%%z%%Z",
2592 "%H%I%k%l%M%N%p%P%r%R%s%S%T%X%z%Z\n",
2593 ),
2594 // Date conversion specifiers
2595 (
2596 "+%%a%%A%%b%%B%%c%%C%%d%%D%%e%%F%%g%%G%%h%%j%%m%%u%%U%%V%%w%%W%%x%%y%%Y",
2597 "%a%A%b%B%c%C%d%D%e%F%g%G%h%j%m%u%U%V%w%W%x%y%Y\n",
2598 ),
2599 ];
2600 for (format, expected) in cases {
2601 new_ucmd!()
2602 .env("TZ", "UTC")
2603 .arg(format)
2604 .succeeds()
2605 .stdout_is(expected);
2606 new_ucmd!()
2607 .env("TZ", "UTC")
2608 .env("LC_ALL", "fr_FR.UTF-8")
2609 .arg(format)
2610 .succeeds()
2611 .stdout_is(expected);
2612 }
2613 }
2614
2615 #[test]
2616 #[cfg(target_os = "linux")]
2617 fn test_date_write_error_dev_full() {
2618 use std::fs::OpenOptions;
2619 let dev_full = OpenOptions::new().write(true).open("/dev/full").unwrap();
2620 new_ucmd!()
2621 .arg("+%s")
2622 .set_stdout(dev_full)
2623 .fails()
2624 .stderr_contains("write error");
2625 }
2626
2627 // Tests for leap year overflow in date arithmetic
2628 #[test]
2629 fn test_date_leap_year_arithmetic_overflow() {
2630 // Adding years to Feb 29 should overflow to March 1
2631 // if target year is not a leap year
2632 new_ucmd!()
2633 .args(&["--date", "02/29/2000 1 year", "+%Y-%m-%d"])
2634 .succeeds()
2635 .stdout_is("2001-03-01\n");
2636
2637 // Additional cases: 2 years
2638 new_ucmd!()
2639 .args(&["--date", "2000-02-29 + 2 years", "+%Y-%m-%d"])
2640 .succeeds()
2641 .stdout_is("2002-03-01\n");
2642
2643 // Leap year to leap year should not overflow
2644 new_ucmd!()
2645 .args(&["--date", "2000-02-29 + 4 years", "+%Y-%m-%d"])
2646 .succeeds()
2647 .stdout_is("2004-02-29\n");
2648 }
2649
2650 // Tests for month arithmetic precision
2651 #[test]
2652 fn test_date_month_subtraction_keeps_day() {
2653 // Subtracting months should maintain same day of month
2654 new_ucmd!()
2655 .args(&[
2656 "--date",
2657 "2003-08-31 12:00:00 +0 7 months ago",
2658 "+%Y-%m-%d %T",
2659 ])
2660 .succeeds()
2661 .stdout_contains("2003-01-31");
2662
2663 // Month overflow: Adding months should overflow to next month if day doesn't exist
2664 new_ucmd!()
2665 .args(&["--date", "1996-01-31 + 1 month", "+%Y-%m-%d"])
2666 .succeeds()
2667 .stdout_is("1996-03-02\n");
2668 }
2669
2670 // Tests for embedded timezone parsing
2671 #[test]
2672 fn test_date_embedded_timezone_conversion() {
2673 // Parse date with embedded timezone
2674 // Date should be interpreted in embedded TZ, then displayed in environment TZ
2675 new_ucmd!()
2676 .env("TZ", "UTC0")
2677 .env("LC_ALL", "C")
2678 .args(&["-d", r#"TZ="CET-1" 1970-01-01 00:00"#])
2679 .succeeds()
2680 .stdout_contains("Dec 31")
2681 .stdout_contains("23:00:00")
2682 .stdout_contains("1969");
2683 }
2684
2685 // Tests for invalid UTF-8 in date string
2686 #[test]
2687 #[cfg(unix)]
2688 fn test_date_invalid_utf8_byte_rejected() {
2689 use std::os::unix::ffi::OsStrExt;
2690
2691 // Invalid UTF-8 byte (0xb0) should produce
2692 // GNU-compatible error message with octal escape sequence
2693 let invalid_bytes = b"\xe0";
2694 let invalid_arg = std::ffi::OsStr::from_bytes(invalid_bytes);
2695
2696 new_ucmd!()
2697 .args(&[std::ffi::OsStr::new("-d"), invalid_arg])
2698 .fails()
2699 .code_is(1)
2700 .stderr_contains("invalid date '\\340'");
2701 }
2702
2703 // Tests for GNU format modifiers
2704 #[test]
2705 fn test_date_format_modifier_width() {
2706 // Test width modifier: %10Y should pad year to 10 digits
2707 new_ucmd!()
2708 .env("TZ", "UTC")
2709 .args(&["-d", "1999-06-01", "+%10Y"])
2710 .succeeds()
2711 .stdout_is("0000001999\n");
2712 }
2713
2714 #[test]
2715 fn test_date_format_modifier_underscore_padding() {
2716 // Test underscore flag: %_10m should pad month with spaces
2717 new_ucmd!()
2718 .env("TZ", "UTC")
2719 .args(&["-d", "1999-06-01", "+%_10m"])
2720 .succeeds()
2721 .stdout_is(" 6\n");
2722 }
2723
2724 #[test]
2725 fn test_date_format_modifier_no_pad() {
2726 // Test no-pad flag: %-10Y suppresses all padding (width ignored)
2727 new_ucmd!()
2728 .env("TZ", "UTC")
2729 .args(&["-d", "1999-06-01", "+%-10Y"])
2730 .succeeds()
2731 .stdout_is("1999\n");
2732
2733 // Test no-pad on day: %-d strips default zero padding
2734 new_ucmd!()
2735 .env("TZ", "UTC")
2736 .args(&["-d", "1999-06-01", "+%-d"])
2737 .succeeds()
2738 .stdout_is("1\n");
2739 }
2740
2741 #[test]
2742 fn test_date_format_modifier_uppercase() {
2743 // Test uppercase flag: %^B should uppercase month name
2744 new_ucmd!()
2745 .env("TZ", "UTC")
2746 .env("LC_ALL", "C")
2747 .args(&["-d", "1999-06-01", "+%^B"])
2748 .succeeds()
2749 .stdout_is("JUNE\n");
2750 }
2751
2752 #[test]
2753 fn test_date_format_modifier_force_sign() {
2754 // Test force sign flag: %+6Y should show + sign for positive years
2755 new_ucmd!()
2756 .env("TZ", "UTC")
2757 .args(&["-d", "1970-01-01", "+%+6Y"])
2758 .succeeds()
2759 .stdout_is("+01970\n");
2760 }
2761
2762 #[test]
2763 fn test_date_format_modifier_combined_flags() {
2764 // Test combined flags: %-^10B should uppercase, no-pad suppresses all padding
2765 new_ucmd!()
2766 .env("TZ", "UTC")
2767 .env("LC_ALL", "C")
2768 .args(&["-d", "1999-06-01", "+%-^10B"])
2769 .succeeds()
2770 .stdout_is("JUNE\n");
2771 }
2772
2773 #[test]
2774 fn test_date_format_modifier_case_precedence() {
2775 // Test that ^ (uppercase) takes precedence over # (swap case) regardless of order
2776 new_ucmd!()
2777 .env("TZ", "UTC")
2778 .env("LC_ALL", "C")
2779 .args(&["-d", "1999-06-01", "+%^#B"])
2780 .succeeds()
2781 .stdout_is("JUNE\n");
2782
2783 new_ucmd!()
2784 .env("TZ", "UTC")
2785 .env("LC_ALL", "C")
2786 .args(&["-d", "1999-06-01", "+%#^B"])
2787 .succeeds()
2788 .stdout_is("JUNE\n");
2789 }
2790
2791 #[test]
2792 fn test_date_format_modifier_multiple() {
2793 // Test multiple modifiers in one format string
2794 // %-5d: no-pad suppresses all padding → "1"
2795 new_ucmd!()
2796 .env("TZ", "UTC")
2797 .args(&["-d", "1999-06-01", "+%10Y-%_5m-%-5d"])
2798 .succeeds()
2799 .stdout_is("0000001999- 6-1\n");
2800 }
2801
2802 #[test]
2803 fn test_date_format_modifier_percent_escape() {
2804 // Test that %% is preserved correctly with modifiers
2805 new_ucmd!()
2806 .env("TZ", "UTC")
2807 .args(&["-d", "1999-06-01", "+%%Y=%10Y"])
2808 .succeeds()
2809 .stdout_is("%Y=0000001999\n");
2810 }
2811
2812 #[test]
2813 fn test_date_format_modifier_huge_width_fails_without_abort() {
2814 // GNU date also exits with failure for extremely large width.
2815 // Assert exit code only to avoid coupling to implementation-specific error text.
2816 let format = format!("+%{}c", usize::MAX);
2817 new_ucmd!().arg(&format).fails().code_is(1);
2818 }
2819
2820 #[test]
2821 fn test_date_format_modifier_parseable_huge_width_fails_without_hanging() {
2822 // Target pointer width can affect the reported parsed width, so assert the
2823 // stable diagnostic shape instead of the exact oversized literal.
2824 new_ucmd!()
2825 .arg("+%8888888888888s")
2826 .fails()
2827 .code_is(1)
2828 .stderr_contains("format modifier width '")
2829 .stderr_contains("' is too large for specifier '%s'");
2830 }
2831
2832 #[test]
2833 fn test_date_format_large_width_no_oom() {
2834 // Regression: very large width like %8888888888r caused OOM.
2835 // Cap supported widths well below that so we don't crash.
2836 // Use a moderate width with a fixed date to check the code path works.
2837 new_ucmd!()
2838 .arg("-d")
2839 .arg("2024-01-01")
2840 .arg("+%300S")
2841 .succeeds()
2842 .stdout_is(format!("{}\n", format_args!("{:0>300}", "00")));
2843
2844 // Test with a larger width to exercise the code path without producing
2845 // gigabytes of output (the original %8888888888r would produce ~2GB).
2846 new_ucmd!()
2847 .arg("-d")
2848 .arg("2024-01-01")
2849 .arg("+%10000S")
2850 .succeeds()
2851 .stdout_is(format!("{}\n", format_args!("{:0>10000}", "00")));
2852
2853 // Mixed literal text with multiple width-modified specifiers.
2854 // 2024-01-01 is Monday (day-of-week 1).
2855 // %2u → "01", literal "ueuu", %6666u → "1" zero-padded to 6666, literal "-r".
2856 let expected = format!("01ueuu{}-r\n", format_args!("{:0>6666}", "1"));
2857 new_ucmd!()
2858 .arg("-d")
2859 .arg("2024-01-01")
2860 .arg("+%2uueuu%6666u-r")
2861 .succeeds()
2862 .stdout_is(expected);
2863 }
2864
2865 // Tests for format modifier edge cases (flags without explicit width)
2866 #[test]
2867 fn test_date_format_modifier_edge_cases() {
2868 // Test cases: (date, format, expected_output, description)
2869 let cases = vec![
2870 // Underscore flag without explicit width (uses default width)
2871 ("1999-06-01", "%_d", " 1", "%_d pads day to default width 2"),
2872 (
2873 "1999-06-15",
2874 "%_m",
2875 " 6",
2876 "%_m pads month to default width 2",
2877 ),
2878 (
2879 "1999-06-01 05:00:00",
2880 "%_H",
2881 " 5",
2882 "%_H pads hour to default width 2",
2883 ),
2884 (
2885 "1999-06-01",
2886 "%_Y",
2887 "1999",
2888 "%_Y year already at default width 4",
2889 ),
2890 (
2891 "1999-06-01",
2892 "%_C",
2893 "19",
2894 "%_C century uses default width 2",
2895 ),
2896 ("2024-06-01", "%_C", "20", "%_C century for year 2024"),
2897 (
2898 "1999-01-01",
2899 "%_j",
2900 " 1",
2901 "%_j pads day-of-year to default width 3",
2902 ),
2903 ("1999-04-10", "%_j", "100", "%_j day 100 already at width 3"),
2904 // Zero flag on space-padded specifiers (overrides default padding)
2905 (
2906 "1999-06-05",
2907 "%0e",
2908 "05",
2909 "%0e overrides space-padding with zero",
2910 ),
2911 (
2912 "1999-06-01 05:00:00",
2913 "%0k",
2914 "05",
2915 "%0k overrides space-padding with zero",
2916 ),
2917 (
2918 "1999-06-01 05:00:00",
2919 "%0l",
2920 "05",
2921 "%0l overrides space-padding with zero",
2922 ),
2923 // Zero flag without explicit width (uses default width)
2924 (
2925 "1999-06-01",
2926 "%0d",
2927 "01",
2928 "%0d day with zero padding (default width 2)",
2929 ),
2930 (
2931 "1999-06-15",
2932 "%0m",
2933 "06",
2934 "%0m month with zero padding (default width 2)",
2935 ),
2936 (
2937 "1999-01-01",
2938 "%0j",
2939 "001",
2940 "%0j day-of-year with zero padding (default width 3)",
2941 ),
2942 // Space-padded specifiers default behavior (no modifier)
2943 ("1999-06-05", "%e", " 5", "%e defaults to space padding"),
2944 (
2945 "1999-06-01 05:00:00",
2946 "%k",
2947 " 5",
2948 "%k defaults to space padding",
2949 ),
2950 (
2951 "1999-06-01 05:00:00",
2952 "%l",
2953 " 5",
2954 "%l defaults to space padding",
2955 ),
2956 // Plus flag without explicit width
2957 (
2958 "1999-06-01",
2959 "%+Y",
2960 "1999",
2961 "%+Y no sign for 4-digit year without width",
2962 ),
2963 (
2964 "1999-06-01",
2965 "%+6Y",
2966 "+01999",
2967 "%+6Y with explicit width adds sign",
2968 ),
2969 ];
2970
2971 for (date, format, expected, description) in cases {
2972 let result = new_ucmd!()
2973 .env("TZ", "UTC")
2974 .args(&["-d", date, &format!("+{format}")])
2975 .succeeds();
2976 // stdout includes newline, expected is without newline
2977 assert_eq!(
2978 result.stdout_str(),
2979 format!("{expected}\n"),
2980 "{description}"
2981 );
2982 }
2983 }
2984
2985 // Tests for --debug flag
2986 #[test]
2987 fn test_date_debug_basic() {
2988 // Test that --debug outputs to stderr, not stdout
2989 let result = new_ucmd!()
2990 .env("TZ", "UTC")
2991 .args(&["--debug", "-d", "2005-01-01", "+%Y"])
2992 .succeeds();
2993
2994 // Stdout should contain only the formatted date
2995 assert_eq!(result.stdout_str().trim(), "2005");
2996
2997 // Stderr should contain debug information
2998 let stderr = result.stderr_str();
2999 assert!(stderr.contains("date: input string:"));
3000 assert!(stderr.contains("date: parsed date part:"));
3001 assert!(stderr.contains("date: parsed time part:"));
3002 assert!(stderr.contains("date: input timezone:"));
3003 }
3004
3005 #[test]
3006 fn test_date_debug_various_formats() {
3007 // Test debug mode with various date formats and expected output
3008 let test_cases = [
3009 // (input, format, expected_stdout_contains, expected_stderr_contains, stderr_not_contains, check_input_string)
3010 (
3011 "2005-01-01 +345 day",
3012 "+%Y-%m-%d",
3013 "2005-12-12",
3014 "date: parsed date part: (Y-M-D) 2005-12-12",
3015 "",
3016 true,
3017 ),
3018 (
3019 "@0",
3020 "+%Y-%m-%d",
3021 "1970-01-01",
3022 "date: parsed date part: (Y-M-D) 1970-01-01",
3023 "warning: using midnight",
3024 true,
3025 ),
3026 (
3027 "@-22",
3028 "+%s",
3029 "-22",
3030 "date: parsed date part: (Y-M-D) 1969-12-31",
3031 "",
3032 true,
3033 ),
3034 (
3035 "2021-03-20 14:53:01 EST",
3036 "+%Y-%m-%d",
3037 "2021-03-20",
3038 "date: parsed date part: (Y-M-D) 2021-03-20",
3039 "",
3040 true,
3041 ),
3042 (
3043 "m9",
3044 "+%T",
3045 "21:00:00",
3046 "date: parsed time part:",
3047 "",
3048 false,
3049 ), // Military TZ is composed before parsing
3050 (
3051 " ",
3052 "+%T",
3053 "00:00:00",
3054 "date: warning: using midnight",
3055 "",
3056 false,
3057 ), // Whitespace is composed
3058 (
3059 "1 day ago",
3060 "+%Y-%m-%d",
3061 "",
3062 "date: parsed date part: (Y-M-D)",
3063 "",
3064 true,
3065 ),
3066 ];
3067
3068 for (
3069 input,
3070 format,
3071 stdout_contains,
3072 stderr_contains,
3073 stderr_not_contains,
3074 check_input_string,
3075 ) in test_cases
3076 {
3077 let result = new_ucmd!()
3078 .env("TZ", "UTC")
3079 .args(&["--debug", "-d", input, format])
3080 .succeeds();
3081
3082 if !stdout_contains.is_empty() {
3083 assert!(
3084 result.stdout_str().contains(stdout_contains),
3085 "For input '{input}': stdout should contain '{stdout_contains}', got: {}",
3086 result.stdout_str()
3087 );
3088 }
3089
3090 let stderr = result.stderr_str();
3091 assert!(
3092 stderr.contains(stderr_contains),
3093 "For input '{input}': stderr should contain '{stderr_contains}'"
3094 );
3095
3096 if check_input_string {
3097 assert!(
3098 stderr.contains(&format!("date: input string: {input}")),
3099 "For input '{input}': stderr should contain input string"
3100 );
3101 } else {
3102 // Just check that there is some input string
3103 assert!(
3104 stderr.contains("date: input string:"),
3105 "For input '{input}': stderr should contain some input string"
3106 );
3107 }
3108
3109 if !stderr_not_contains.is_empty() {
3110 assert!(
3111 !stderr.contains(stderr_not_contains),
3112 "For input '{input}': stderr should not contain '{stderr_not_contains}'"
3113 );
3114 }
3115 }
3116 }
3117
3118 #[test]
3119 fn test_date_debug_midnight_warnings() {
3120 // Test midnight warning behavior with various inputs
3121 let test_cases = [
3122 // (input, format, should_warn)
3123 ("2005-01-01", "+%Y", true), // No time specified
3124 ("1997-01-19 08:17:48 +0", "+%Y-%m-%d", false), // Time specified
3125 ("@0", "+%Y-%m-%d", false), // Epoch format
3126 (" ", "+%T", true), // Whitespace (defaults to midnight)
3127 ];
3128
3129 for (input, format, should_warn) in test_cases {
3130 let result = new_ucmd!()
3131 .env("TZ", "UTC")
3132 .args(&["--debug", "-d", input, format])
3133 .succeeds();
3134
3135 let stderr = result.stderr_str();
3136 if should_warn {
3137 assert!(
3138 stderr.contains("date: warning: using midnight"),
3139 "Input '{input}' should produce midnight warning"
3140 );
3141 } else {
3142 assert!(
3143 !stderr.contains("warning: using midnight"),
3144 "Input '{input}' should not produce midnight warning"
3145 );
3146 }
3147 }
3148 }
3149
3150 #[test]
3151 fn test_date_debug_without_flag() {
3152 // Test that without --debug, no debug output appears
3153 let result = new_ucmd!()
3154 .env("TZ", "UTC")
3155 .args(&["-d", "2005-01-01", "+%Y"])
3156 .succeeds();
3157
3158 let stderr = result.stderr_str();
3159 assert!(!stderr.contains("date: input string:"));
3160 assert!(!stderr.contains("date: parsed date part:"));
3161 }
3162
3163 #[test]
3164 fn test_date_debug_with_multiple_inputs() {
3165 // Test debug mode with file and stdin input (multiple dates)
3166 let (at, mut ucmd) = at_and_ucmd!();
3167 let file = "debug_test_file";
3168 at.write(file, "2005-01-01\n2006-02-02\n");
3169
3170 let result = ucmd
3171 .env("TZ", "UTC")
3172 .args(&["--debug", "-f", file, "+%Y"])
3173 .succeeds();
3174
3175 assert_eq!(result.stdout_str(), "2005\n2006\n");
3176
3177 let stderr = result.stderr_str();
3178 // Should show debug output for both lines
3179 assert!(stderr.contains("date: input string: 2005-01-01"));
3180 assert!(stderr.contains("date: input string: 2006-02-02"));
3181 assert!(stderr.contains("date: parsed date part: (Y-M-D) 2005-01-01"));
3182 assert!(stderr.contains("date: parsed date part: (Y-M-D) 2006-02-02"));
3183
3184 // Test with stdin
3185 let result = new_ucmd!()
3186 .env("TZ", "UTC")
3187 .args(&["--debug", "-f", "-", "+%Y"])
3188 .pipe_in("2005-01-01\n2006-02-02\n")
3189 .succeeds();
3190
3191 assert_eq!(result.stdout_str(), "2005\n2006\n");
3192 let stderr = result.stderr_str();
3193 assert!(stderr.contains("date: input string: 2005-01-01"));
3194 assert!(stderr.contains("date: input string: 2006-02-02"));
3195 }
3196
3197 #[test]
3198 fn test_date_debug_with_flags() {
3199 // Test debug mode combined with other flags and exit codes
3200 let test_cases = [
3201 // (args, should_succeed, stdout_contains, stderr_contains)
3202 (
3203 vec!["--debug", "-d", "2005-01-01", "+%Y"],
3204 true,
3205 "2005",
3206 "date: input string:",
3207 ),
3208 (
3209 vec!["--debug", "-u", "-d", "2005-01-01", "+%Y-%m-%d %Z"],
3210 true,
3211 "UTC",
3212 "date: parsed date part:",
3213 ),
3214 (
3215 vec!["--debug", "-R", "-d", "2005-01-01"],
3216 true,
3217 "Sat, 01 Jan 2005",
3218 "date: input string:",
3219 ),
3220 (
3221 vec!["--debug", "-d", "invalid", "+%Y"],
3222 false,
3223 "",
3224 "invalid date",
3225 ),
3226 ];
3227
3228 for (args, should_succeed, stdout_contains, stderr_contains) in test_cases {
3229 let mut cmd = new_ucmd!();
3230 cmd.env("TZ", "UTC").args(&args);
3231
3232 if should_succeed {
3233 let result = cmd.succeeds();
3234 assert!(
3235 result.stdout_str().contains(stdout_contains),
3236 "Args {args:?}: stdout should contain '{stdout_contains}'"
3237 );
3238 assert!(
3239 result.stderr_str().contains(stderr_contains),
3240 "Args {args:?}: stderr should contain '{stderr_contains}'"
3241 );
3242 } else {
3243 let result = cmd.fails();
3244 assert!(
3245 result.stderr_str().contains(stderr_contains),
3246 "Args {args:?}: stderr should contain '{stderr_contains}'"
3247 );
3248 }
3249 }
3250 }
3251
3252 #[test]
3253 fn test_date_debug_current_time() {
3254 // Test that debug mode without -d doesn't produce debug output (no parsing)
3255 let result = new_ucmd!()
3256 .env("TZ", "UTC")
3257 .args(&["--debug", "+%Y"])
3258 .succeeds();
3259
3260 let stderr = result.stderr_str();
3261 // No parsing happens for "now", so no debug output
3262 assert_eq!(stderr, "");
3263 }
3264
3265 #[test]
3266 fn test_korean_time_zone() {
3267 // KST (UTC+9 korean standard time) used in winter
3268 new_ucmd!()
3269 .env("TZ", "UTC")
3270 .arg("-u")
3271 .arg("-d")
3272 .arg("2026-01-15 10:00 KST")
3273 .arg("+%F %T %Z")
3274 .succeeds()
3275 .stdout_is("2026-01-15 01:00:00 UTC\n");
3276 }
3277
3278 // https://github.com/uutils/coreutils/issues/12001
3279 // date: width prefix in %N format specifier is ignored ( %3N, %6N always output full 9 nanosecond digits) #12001
3280 #[test]
3281 fn test_nanoseconds_width_prefix_ignored_issue12001() {
3282 let result = new_ucmd!().arg("+%3N").succeeds();
3283 // compare to 4 because of \n
3284 assert_eq!(result.stdout().len(), 4);
3285 }
3286
3287 #[test]
3288 #[cfg(target_os = "linux")]
3289 #[cfg_attr(wasi_runner, ignore)]
3290 fn test_write_error() {
3291 use std::fs::OpenOptions;
3292
3293 let dev_full = OpenOptions::new().write(true).open("/dev/full").unwrap();
3294
3295 new_ucmd!()
3296 .set_stdout(dev_full)
3297 .fails_with_code(1)
3298 .stderr_is("date: write error: No space left on device\n");
3299 }