date: -d empty string should be treated as midnight today

This commit is contained in:
Sylvestre Ledru 2025-10-25 22:06:13 +02:00
parent 284554658d
commit 5cae9ae53e
2 changed files with 35 additions and 4 deletions

View file

@ -205,6 +205,11 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
// Iterate over all dates - whether it's a single date or a file.
let dates: Box<dyn Iterator<Item = _>> = match settings.date_source {
DateSource::Human(ref input) => {
let input = input.trim();
// GNU compatibility (Empty string):
// An empty string (or whitespace-only) should be treated as midnight today.
let is_empty_or_whitespace = input.is_empty();
// GNU compatibility (Military timezone 'J'):
// 'J' is reserved for local time in military timezones.
// GNU date accepts it and treats it as midnight today (00:00:00).
@ -218,8 +223,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let is_pure_digits =
!input.is_empty() && input.len() <= 4 && input.chars().all(|c| c.is_ascii_digit());
let date = if is_military_j {
// Treat 'J' as midnight today (00:00:00) in local time
let date = if is_empty_or_whitespace || is_military_j {
// Treat empty string or 'J' as midnight today (00:00:00) in local time
let date_part =
strtime::format("%F", &now).unwrap_or_else(|_| String::from("1970-01-01"));
let offset = if settings.utc {

View file

@ -973,8 +973,7 @@ fn test_date_military_timezone_j_variations() {
}
#[test]
#[ignore = "we use current time, GNU uses midnight"]
fn test_date_fuzz_empty_string() {
fn test_date_empty_string() {
// Empty string should be treated as midnight today
new_ucmd!()
.env("TZ", "UTC+1")
@ -984,6 +983,33 @@ fn test_date_fuzz_empty_string() {
.stdout_contains("00:00:00");
}
#[test]
fn test_date_empty_string_variations() {
// Test multiple variations of empty/whitespace strings
// All should produce midnight (00:00:00)
let test_cases = vec!["", " ", " ", "\t", "\n", " \t ", "\t\n\t"];
for input in test_cases {
new_ucmd!()
.env("TZ", "UTC")
.arg("-d")
.arg(input)
.arg("+%T")
.succeeds()
.stdout_is("00:00:00\n");
}
// Test with -u flag to verify UTC behavior
new_ucmd!()
.arg("-u")
.arg("-d")
.arg("")
.arg("+%T %Z")
.succeeds()
.stdout_contains("00:00:00")
.stdout_contains("UTC");
}
#[test]
#[ignore = "we produce year 0008, GNU gives today 12:00"]
fn test_date_fuzz_relative_m9() {