PHP Function Reference

PHP DateTime - getTimestamp() Method



The PHP DateTime::getTimestamp() method returns the Unix timestamp representing the date. The date_timestamp_get() function is an alias of this method.

Note: This method is defined under DateTimeInterface interface. DateTime and DateTimeImmutable classes inherit this method from DateTimeInterface interface.

Note: Unix timestamp indicates the number of seconds since midnight of January 1, 1970 (Gregorian Calendar).

Syntax

//Object-oriented style
public DateTime::getTimestamp()
public DateTimeImmutable::getTimestamp()
public DateTimeInterface::getTimestamp()

//Procedural style
date_timestamp_get(object)

Parameters

object Required. For procedural style only: A DateTime object returned by date_create().

Return Value

Returns the Unix timestamp representing the date.

Example: using both styles

The example below shows the usage of DateTime::getTimestamp() method.

<?php
  //datetime string
  $datetime_string = "14-Dec-2015 10:15";

  //creating a DateTime object
  $date = new DateTime($datetime_string);

  //getting the Unix timestamp using Object-oriented style
  echo "TimeStamp: ".$date->getTimestamp()."\n";

  //getting the Unix timestamp using Procedural style
  echo "TimeStamp: ".date_timestamp_get($date)."\n";
?>

The output of the above code will be:

TimeStamp: 1450088100
TimeStamp: 1450088100

Example: Unix timestamp of a DateTime object

Consider the example below where the Unix timestamp of a DateTime object is returned using this method.

<?php
  //datetime string
  $datetime_string = "14-May-2015 10:15:28 GMT+2";

  //creating a DateTime object
  $date = new DateTime($datetime_string);

  //getting the Unix timestamp
  echo "Initial TimeStamp: ".$date->getTimestamp()."\n";

   //Adding interval (5 years 3 months) to the date
   $date->add(new DateInterval('P5Y3M'));

  //getting the Unix timestamp
  echo "Final TimeStamp: ".$date->getTimestamp()."\n";
?>

The output of the above code will be:

Initial TimeStamp: 1431591328
Final TimeStamp: 1597392928

Example: Unix timestamp of a DateTimeImmutable object

Similarly, this method can be used with DateTimeImmutable object also. Consider the example below:

<?php
  //datetime string
  $datetime_string = "14-May-2015 10:15:28 GMT+2";

  //creating a DateTimeImmutable object
  $date = new DateTimeImmutable($datetime_string);

  //getting the Unix timestamp
  echo "TimeStamp: ".$date->getTimestamp()."\n";
?>

The output of the above code will be:

TimeStamp: 1431591328

❮ PHP Date and Time Reference