DateTime::getTimestamp()
DateTimeImmutable::getTimestamp
DateTimeInterface::getTimestamp
date_timestamp_get
(PHP 5 >= 5.3.0, PHP 7)
Gets the Unix timestamp
说明
面向对象风格public DateTime::getTimestamp(void): int
public DateTimeImmutable::getTimestamp(void): int
public DateTimeInterface::getTimestamp(void): int
过程化风格
date_timestamp_get(DateTimeInterface$object): int
Gets the Unix timestamp.
参数
此函数没有参数。
返回值
Returns the Unix timestamp representing the date.
范例
Example #1DateTime::getTimestamp()example
面向对象风格
<?php $date = new DateTime(); echo $date->getTimestamp(); ?>
过程化风格
<?php $date = date_create(); echo date_timestamp_get($date); ?>
以上例程的输出类似于:
1272509157
注释
UsingUas the parameter toDateTime::format()is an alternative when using PHP 5.2.
参见
- DateTime::setTimestamp() 以 Unix 时间戳的方式设置 DateTime 对象
- DateTime::format() Returns date formatted according to given format
In 32-bit system the unix timestamp will overflow if the date goes beyond year 2038 and this method will return false. In 64-bit systems this function will still work as intended. For more information please see http://en.wikipedia.org/wiki/Year_2038_problem.
Note that for dates before the unix epoch getTimestamp() will return false, whereas format("U") will return a negative number. <?php $date = new DateTime("1899-12-31"); // "-2209078800" echo $date->format("U"); // false echo $date->getTimestamp(); ?>
Miguel's comment is wrong - getTimeStamp() always returns a timestamp, this has nothing to do with timezones at all, as you can see below. What's really happening in Miguel's example, is he is parsing the input dates in different timezones. There is no such thing as "a timestamp relative to the timezone". <?php $d = new DateTime('2016-03-11 11:00:00', new DateTimeZone('Europe/Rome')); var_dump($d->getTimestamp()); // 1457690400 $d->setTimeZone(new DateTimeZone('America/New_York')); var_dump($d->getTimestamp()); // 1457690400
Note that getTimestamp() does not return the UTC timestamp. It returns the timestamp relative to the set timezone, or the default server timezone. This also applies to dates in timezones with Daylight Savings. <?php // 11th March 2016 @ 11:00 UTC has timestamp: 1457694000 $d1 = new DateTime('2016-03-11 11:00:00', new DateTimeZone('Europe/Rome')); $t1 = $d1->getTimestamp(); // 11th April 2016 @ 11:00 UTC has timestamp: 1460372400 $d2 = new DateTime('2016-04-11 11:00:00', new DateTimeZone('Europe/Rome')); $t2 = $d2->getTimestamp(); printf("11 March: %d (diff = %d less)\n", $t1, 1457694000 - $t1); printf("11 April: %d (diff = %d less)", $t2, 1460372400 - $t2); // Prints: // 1457690400 (diff = 3600) // 1460365200 (diff = 7200)