4

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
)
John Conde
  • 217,595
  • 99
  • 455
  • 496
Moon
  • 22,195
  • 68
  • 188
  • 269
  • 1
    possible duplicate of [Is it possible to get UNIX time from such date 2011-02-27 02:04:46?](http://stackoverflow.com/questions/5749319/is-it-possible-to-get-unix-time-from-such-date-2011-02-27-020446) – mario Feb 20 '13 at 02:31

3 Answers3

12
$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');
John Conde
  • 217,595
  • 99
  • 455
  • 496
3

Using U as the parameter to DateTime::format() is an alternative when using PHP 5.2.

$ts = $datetimeObj->format('U');
xdazz
  • 158,678
  • 38
  • 247
  • 274
2

If you would take a look at the manual:

Using U as the parameter to DateTime::format() is an alternative when using PHP 5.2.

So DateTime::format('U') it is.

jeroen
  • 91,079
  • 21
  • 114
  • 132