'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?
Solution 1:[1]
echo (new DateTime())->format('Y-m-d');
Solution 2:[2]
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');
?>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Eugen Dimboiu |
| Solution 2 | Aman Garg |
