在 PHP 网站中获取时间戳非常简单,PHP 提供了多种方法来获取当前时间的时间戳(Unix 时间戳,即自 1970-01-01 00:00:00 UTC 以来的秒数)。以下是几种常见的方法:

1. 使用函数

time()

是最简单的方法,返回当前的 Unix 时间戳。

time()

php

$timestamp = time();

echo
" . $timestamp;

输出示例

当前时间戳: 1727061234

2. 使用函数

strtotime()

可以将英文文本的日期时间描述解析为 Unix 时间戳。

strtotime()

php

$timestamp = strtotime("now"); // 当前时间

echo "当前时间戳: " . $timestamp;

$timestamp2 = strtotime("2024-01-01 12:00:00"); // 指定时间

echo "\n指定时间戳: " . $timestamp2;

输出示例

当前时间戳: 1727061234

指定时间戳: 1704110400

3. 使用类(PHP 5.2+)

DateTime

类提供了更面向对象的方式获取时间戳。

DateTime

php

$date = new DateTime(); // 当前时间

$timestamp = $date->getTimestamp();

echo "当前时间戳: " . $timestamp;

$date2 = new DateTime("2024-01-01 12:00:00"); // 指定时间

$timestamp2 = $date2->getTimestamp();

echo "\n指定时间戳: " . $timestamp2;

输出示例

当前时间戳: 1727061234

指定时间戳: 1704110400