The getTimestamp Method of the DateTime Class

The getTimestamp method returns the Unix timestamp for an object of the DateTime class. This is an integer representing the number of seconds that have passed from 00:00:00 UTC January 1, 1970, to the specified date. The method does not take any parameters.

Syntax

php$datetime->getTimestamp();

Example

Get the current timestamp:

php<?php
  $date = new DateTime();
  echo $date->getTimestamp();
?>

Code execution result:

php1678901234

Example

Get the timestamp for a specific date:

php<?php
  $date = new DateTime('2023-01-15 12:00:00');
  echo $date->getTimestamp();
?>

Code execution result:

php1673784000

Example

Compare two dates using their timestamps:

php<?php
  $date1 = new DateTime('2023-01-01');
  $date2 = new DateTime('2023-01-15');
  
  if ($date1->getTimestamp() < $date2->getTimestamp()) {
    echo 'Date1 is earlier than Date2';
  }
?>

Code execution result:

php'Date1 is earlier than Date2'

See Also

  • the format method,
    which formats the date according to a given pattern
  • the time function,
    which returns the current Unix timestamp
  • the modify method,
    which modifies the date of the DateTime object