How to convert only the date without time to a string in PHP

1 Answer

0 votes
/*
    Function: dateToString
    Purpose : Convert a DateTimeInterface to a string (YYYY-MM-DD)
*/
function dateToString(DateTimeInterface $dt): string {
    return $dt->format('Y-m-d');
}

/*
    Function: makeDate
    Purpose : Build a date from integers (year, month, day)
*/
function makeDate(int $y, int $m, int $d): DateTimeImmutable {
    return new DateTimeImmutable("$y-$m-$d");
}

//
// 1. Today's date
//
$today = new DateTimeImmutable('today');
echo "Today's date is: " . dateToString($today) . PHP_EOL;

//
// 2. Hard‑coded date
//
$myDate = makeDate(2025, 12, 7);
echo "Hard-coded date is: " . dateToString($myDate) . PHP_EOL;



/* 
run:

Today's date is: 2026-05-30
Hard-coded date is: 2025-12-07

*/

 



answered 8 hours ago by avibootz

Related questions

...