6

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?

Peter
  • 8,776
  • 6
  • 62
  • 95

3 Answers3

16
echo (new DateTime())->format('Y-m-d');
Eugen Dimboiu
  • 2,733
  • 2
  • 26
  • 33
13

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

danopz
  • 3,310
  • 5
  • 31
  • 42
  • Wow, the parentheses did it. Thank you! – ᴍᴇʜᴏᴠ Apr 01 '20 at 10:14
  • What's the backslash for, dear Sir? – rlatief Jun 07 '22 at 02:48
  • It's an indicator for "global php namespace" and for function it's an optimization for the opcache (performance). You don't need to prefix classes when you are not inside a namespace. Read more about that on SO itself: https://stackoverflow.com/q/4790020/3893182 – danopz Jun 07 '22 at 08:26
-1

You can try this way:

echo $date = new DateTime('2016-01-01');

Object Oriented Style:

<?php
try {
    $date = new DateTime('2000-01-01');
} catch (Exception $e) {
    echo $e->getMessage();
    exit(1);
}

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

Procedural Style:

<?php
$date = date_create('2000-01-01');
if (!$date) {
    $e = date_get_last_errors();
    foreach ($e['errors'] as $error) {
        echo "$error\n";
    }
    exit(1);
}

echo date_format($date, 'Y-m-d');
?>
Aman Garg
  • 3,122
  • 4
  • 24
  • 32
  • Can you explain that further? The first example does not use custom formatting, the later two are obviously no one-liners – Nico Haase Apr 02 '20 at 08:48