PHP date_timestamp_get() 函数

date_timestamp_get() 函数是 DateTime::getTimestamp() 的过程化别名,用于从 DateTime 对象获取 Unix 时间戳。

注意:此函数在 PHP 5.3.0 及以上版本可用。建议使用面向对象风格的 DateTime::getTimestamp() 方法。

语法

date_timestamp_get(DateTimeInterface $object): int

参数

参数 类型 描述
$object DateTimeInterface 必需。DateTime或DateTimeImmutable对象

返回值

返回一个整数,表示从 Unix 纪元(1970-01-01 00:00:00 UTC)到指定时间的秒数。

示例

示例 1:基本用法 - 获取当前时间戳

<?php
// 创建当前时间的DateTime对象
$date = date_create();
echo "当前时间: " . date_format($date, 'Y-m-d H:i:s') . "\n";

// 获取Unix时间戳
$timestamp = date_timestamp_get($date);
echo "Unix时间戳: " . $timestamp . "\n";

// 验证时间戳(将时间戳转换回日期)
echo "从时间戳验证: " . date('Y-m-d H:i:s', $timestamp) . "\n";

// 使用time()函数比较
echo "time()函数结果: " . time() . "\n";
echo "两者差异: " . abs(time() - $timestamp) . " 秒(应该很小)\n";
?>
                            

输出:


当前时间: 2023-12-25 10:30:45
Unix时间戳: 1703500245
从时间戳验证: 2023-12-25 10:30:45
time()函数结果: 1703500245
两者差异: 0 秒(应该很小)
                            
示例 2:处理特定日期时间

<?php
// 创建特定日期时间的DateTime对象
$dates = [
    'Unix纪元' => date_create('1970-01-01 00:00:00 UTC'),
    '2038年问题' => date_create('2038-01-19 03:14:07 UTC'),
    '未来日期' => date_create('2050-12-31 23:59:59 UTC'),
    '历史日期' => date_create('1969-07-20 20:17:00 UTC'), // 阿波罗11号登月
    '闰秒示例' => date_create('2016-12-31 23:59:60 UTC'), // 闰秒
];

foreach ($dates as $name => $date) {
    $timestamp = date_timestamp_get($date);
    echo $name . ":\n";
    echo "  日期时间: " . $date->format('Y-m-d H:i:s') . "\n";
    echo "  时间戳: " . $timestamp . "\n";
    echo "  可读格式: " . date('Y-m-d H:i:s', $timestamp) . "\n";

    // 特殊处理:负时间戳(1970年之前)
    if ($timestamp < 0) {
        echo "  注意:这是1970年之前的日期,时间戳为负数\n";
    }
    echo "\n";
}
?>
                            

输出:


Unix纪元:
  日期时间: 1970-01-01 00:00:00
  时间戳: 0
  可读格式: 1970-01-01 00:00:00

2038年问题:
  日期时间: 2038-01-19 03:14:07
  时间戳: 2147483647
  可读格式: 2038-01-19 03:14:07

未来日期:
  日期时间: 2050-12-31 23:59:59
  时间戳: 2556057599
  可读格式: 2050-12-31 23:59:59

历史日期:
  日期时间: 1969-07-20 20:17:00
  时间戳: -14182980
  可读格式: 1969-07-20 20:17:00
  注意:这是1970年之前的日期,时间戳为负数

闰秒示例:
  日期时间: 2016-12-31 23:59:60
  时间戳: 1483228800
  可读格式: 2017-01-01 00:00:00
                            
重要说明:
  • 2038年问题:32位系统的时间戳最大值是2147483647(2038-01-19 03:14:07 UTC)
  • 负时间戳:1970年之前的日期返回负时间戳,但date()函数在32位系统上可能无法正确处理负时间戳
  • 闰秒:Unix时间戳不考虑闰秒,所以23:59:60会被视为下一分钟的开始
示例 3:实际应用 - 时间戳缓存系统

<?php
/**
 * 带时间戳的缓存项
 */
class CacheItem {
    private $data;
    private $expiryDateTime;

    public function __construct($data, DateTime $expiryDateTime) {
        $this->data = $data;
        $this->expiryDateTime = $expiryDateTime;
    }

    public function getData() {
        return $this->data;
    }

    public function getExpiryTimestamp(): int {
        return date_timestamp_get($this->expiryDateTime);
    }

    public function isExpired(): bool {
        $now = new DateTime();
        return date_timestamp_get($now) >= $this->getExpiryTimestamp();
    }

    public function getTimeToLive(): int {
        $now = new DateTime();
        return $this->getExpiryTimestamp() - date_timestamp_get($now);
    }
}

/**
 * 简单的缓存系统
 */
class TimestampCache {
    private $storage = [];

    public function set(string $key, $value, DateTime $expiryDateTime): void {
        $this->storage[$key] = new CacheItem($value, $expiryDateTime);
    }

    public function get(string $key) {
        if (!isset($this->storage[$key])) {
            return null;
        }

        $item = $this->storage[$key];

        if ($item->isExpired()) {
            unset($this->storage[$key]);
            return null;
        }

        echo "缓存键 '{$key}' 剩余有效期: " . $item->getTimeToLive() . " 秒\n";
        return $item->getData();
    }

    public function getInfo(string $key): ?array {
        if (!isset($this->storage[$key])) {
            return null;
        }

        $item = $this->storage[$key];
        return [
            'expiry_timestamp' => $item->getExpiryTimestamp(),
            'expiry_datetime' => date('Y-m-d H:i:s', $item->getExpiryTimestamp()),
            'ttl_seconds' => $item->getTimeToLive(),
            'is_expired' => $item->isExpired()
        ];
    }
}

// 使用示例
$cache = new TimestampCache();

// 设置缓存项,5分钟后过期
$expiryTime = new DateTime();
$expiryTime->modify('+5 minutes');
$cache->set('user_profile', ['id' => 123, 'name' => '张三'], $expiryTime);

// 设置另一个缓存项,10秒后过期
$shortExpiry = new DateTime();
$shortExpiry->modify('+10 seconds');
$cache->set('api_token', 'abc123xyz', $shortExpiry);

echo "缓存系统演示:\n\n";

// 获取缓存信息
echo "缓存信息:\n";
$info = $cache->getInfo('user_profile');
if ($info) {
    echo "user_profile:\n";
    echo "  过期时间戳: " . $info['expiry_timestamp'] . "\n";
    echo "  过期时间: " . $info['expiry_datetime'] . "\n";
    echo "  剩余秒数: " . $info['ttl_seconds'] . "\n";
    echo "  是否过期: " . ($info['is_expired'] ? '是' : '否') . "\n\n";
}

// 获取缓存数据
echo "获取缓存数据:\n";
$userProfile = $cache->get('user_profile');
echo "user_profile: " . print_r($userProfile, true) . "\n";

// 等待一段时间后再次检查
echo "\n等待3秒后...\n";
sleep(3);

$token = $cache->get('api_token');
if ($token) {
    echo "api_token: " . $token . "\n";
} else {
    echo "api_token: 已过期\n";
}
?>
                            

输出:


缓存系统演示:

缓存信息:
user_profile:
  过期时间戳: 1703500545
  过期时间: 2023-12-25 10:35:45
  剩余秒数: 300
  是否过期: 否

获取缓存数据:
缓存键 'user_profile' 剩余有效期: 300 秒
user_profile: Array
(
    [id] => 123
    [name] => 张三
)

等待3秒后...
缓存键 'api_token' 剩余有效期: 7 秒
api_token: abc123xyz
                            
面向对象风格:DateTime::getTimestamp()

推荐使用面向对象风格的 DateTime::getTimestamp() 方法,代码更清晰:


<?php
// 创建DateTime对象
$date = new DateTime('2023-12-25 14:30:45');

// 获取时间戳
$timestamp = $date->getTimestamp();
echo "日期时间: " . $date->format('Y-m-d H:i:s') . "\n";
echo "时间戳: " . $timestamp . "\n";

// 链式调用示例
$timestamp = (new DateTime('2023-12-25'))
    ->modify('+1 day')
    ->setTime(9, 0, 0)
    ->getTimestamp();

echo "链式调用后时间戳: " . $timestamp . "\n";
echo "对应日期: " . date('Y-m-d H:i:s', $timestamp) . "\n";

// DateTimeImmutable 示例(不可变对象)
$immutableDate = new DateTimeImmutable('2023-06-21 12:00:00');
echo "\nDateTimeImmutable示例:\n";
echo "原始时间: " . $immutableDate->format('Y-m-d H:i:s') . "\n";
echo "时间戳: " . $immutableDate->getTimestamp() . "\n";

// 修改不会影响原对象
$newDate = $immutableDate->modify('+1 month');
echo "修改后时间: " . $newDate->format('Y-m-d H:i:s') . "\n";
echo "原始时间不变: " . $immutableDate->format('Y-m-d H:i:s') . "\n";
?>
                            

输出:


日期时间: 2023-12-25 14:30:45
时间戳: 1703514645
链式调用后时间戳: 1703552400
对应日期: 2023-12-26 09:00:00

DateTimeImmutable示例:
原始时间: 2023-06-21 12:00:00
时间戳: 1687348800
修改后时间: 2023-07-21 12:00:00
原始时间不变: 2023-06-21 12:00:00
                            
推荐:在PHP 5.3及以上版本,强烈建议使用面向对象风格的 DateTime::getTimestamp() 方法,代码更易读且支持链式调用。
常见时间戳参考表
事件 日期时间 Unix时间戳 说明
Unix纪元 1970-01-01 00:00:00 UTC 0 Unix时间起点
2038年问题 2038-01-19 03:14:07 UTC 2147483647 32位系统最大时间戳
Y2K问题 2000-01-01 00:00:00 UTC 946684800 千禧年
PHP诞生 1995-06-08 00:00:00 UTC 802425600 PHP 1.0发布
Windows 95发布 1995-08-24 00:00:00 UTC 809078400 操作系统发布
互联网时代 1991-08-06 00:00:00 UTC 681436800 万维网首次公开

注意事项

  • 时区考虑:Unix时间戳始终基于UTC时区。DateTime对象可能包含其他时区,但getTimestamp()会自动转换为UTC。
  • 32位系统限制:在32位系统上,时间戳范围是1901-12-13到2038-01-19。超出范围的时间戳会导致问题。
  • 精度:返回的是整数秒数,不包含微秒。如果需要微秒精度,使用 DateTime::format('U.u')
  • 性能:对于简单的当前时间戳,time() 函数比创建DateTime对象更高效。
  • 不可变对象:DateTimeImmutable对象也支持此方法,且不会修改原对象。
  • 闰秒:Unix时间戳忽略闰秒,可能与实际天文时间有微小差异。
  • 2038年问题:确保系统使用64位整数处理时间戳,以避免2038年问题。

相关函数

time()

返回当前的Unix时间戳

strtotime()

将英文文本日期时间解析为Unix时间戳

date()

格式化Unix时间戳

DateTime::getTimestamp()

面向对象风格的获取时间戳方法

date_timestamp_set()

设置DateTime对象的Unix时间戳

microtime()

返回当前Unix时间戳和微秒数