Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a unix timestamp from DateTime object with PHP 5.2?

Tags:

date

php

datetime

I'm working on a few years old codebase and it uses DateTime. The server is using PHP 5.2.

I see that DateTime::getTimestamp() has been added after PHP 5.3.

Is it possible to get a timestamp from DateTime in PHP 5.2?

I used get_class_methods to see if the method is available, but it's not.

Array
(
    [0] => __construct
    [1] => format
    [2] => modify
    [3] => getTimezone
    [4] => setTimezone
    [5] => getOffset
    [6] => setTime
    [7] => setDate
    [8] => setISODate
)
like image 951
Moon Avatar asked Dec 04 '22 00:12

Moon


1 Answers

$datetime = new DateTime();
echo $datetime->format('U');

See it in action

edit

As of PHP 5.4 you can make this a one-liner:

echo (new DateTime())->format('U');
like image 197
John Conde Avatar answered Dec 26 '22 05:12

John Conde