在 PHP 中获取时间戳的方法:time() 函数:返回当前时间自 Unix 纪元以来的秒数。date() 函数:接受格式字符串作为参数,其中 U 表示时间戳格式。DateTime 类:可获取特定时区的时间戳。microtime() 函数:返回微秒级的时间戳(浮点数)。

PHP 获取时间戳
在 PHP 中,获取时间戳非常简单。可以通过以下方法实现:
time() 函数
time() 函数返回当前时间的时间戳,以自 Unix 纪元(1970 年 1 月 1 日午夜 UTC)以来经过的秒数表示。
立即学习“PHP免费学习笔记(深入)”;
<code class="php">$timestamp = time(); echo $timestamp; // 输出:1678944306</code>
date() 函数
还可以使用 date() 函数获取指定格式的时间戳。该函数接受一个格式字符串作为参数,其中 U 表示时间戳格式。
<code class="php">$timestamp = date('U');
echo $timestamp; // 输出:1678944306</code>获取特定时区的时间戳
如果需要获取特定时区的时间戳,可以使用 DateTime 类。
<code class="php">$timezone = 'Asia/Shanghai';
$datetime = new DateTime('now', new DateTimeZone($timezone));
$timestamp = $datetime->getTimestamp();
echo $timestamp; // 输出:1678952306</code>获取微秒级时间戳
如果需要获取微秒级的时间戳,可以使用 microtime() 函数。该函数返回一个字符串,其中包含当前时间的时间戳(浮点数)。
<code class="php">$timestamp = microtime(true); echo $timestamp; // 输出:1678944306.3456</code>
需要注意的是:
以上就是php如何获取时间戳的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号