Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using DateTime as a one-liner in PHP

Tags:

date

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?

like image 913
Peter Avatar asked Oct 10 '16 08:10

Peter


2 Answers

echo (new DateTime())->format('Y-m-d');
like image 156
Eugen Dimboiu Avatar answered Sep 30 '22 22:09

Eugen Dimboiu


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

like image 41
danopz Avatar answered Sep 30 '22 23:09

danopz