Skip to content
Advertisement

Using DateTime as a one-liner in PHP

A short and simple question which I couldn’t really find an answer for.

In procedural PHP I could echo a date

echo date('Y-m-d'); ?>

In Object oriented PHP I have to use two lines

$now = new DateTime();
echo $now->format('Y-m-d');

Is it possible to do this in one line?

Advertisement

Answer

There are two options:

  1. Create a DateTime instance using parenthesis and format the result:

    // requires PHP >= 5.4
    echo (new DateTime())->format('Y-m-d');
    
  2. You can use the date_create function:

    // date_create is similar to new DateTime()
    echo date_create()->format('Y-m-d');
    

Live Example: https://3v4l.org/fllco

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement