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
$datetime->getTimestamp();
Example
Get the current timestamp:
<?php
$date = new DateTime();
echo $date->getTimestamp();
?>
Code execution result:
1678901234
Example
Get the timestamp for a specific date:
<?php
$date = new DateTime('2023-01-15 12:00:00');
echo $date->getTimestamp();
?>
Code execution result:
1673784000
Example
Compare two dates using their timestamps:
<?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:
'Date1 is earlier than Date2'