PHP:获取时间戳,时间,以及相关转换

一、获取当前时间戳

php 复制代码
// 获取当前时间的时间戳(秒级,11位)
$currentTimestampInSeconds = time();

二、秒级(11位)时间戳转换为毫秒级(13位)时间戳

乘以1000即可

php 复制代码
// 转换为毫秒时间戳(13位)
$millisecondsTimestamp = $currentTimestampInSeconds * 1000;

三、将时间戳转换为日期时间字符串

php 复制代码
// 秒级时间戳:假设有一个时间戳
$timestampInSeconds = 1659853800;
// 使用 date 函数将其转换为日期时间字符串
$dateTimeString = date("Y-m-d H:i:s", $timestampInSeconds);

// 毫秒级时间戳:若要以毫秒级时间戳转换,首先除以1000获得秒级时间戳
$timestampInMilliseconds = 1659853800000;
$timestampInSeconds = floor($timestampInMilliseconds / 1000);
// 然后同上,转换为日期时间字符串
$dateTimeString = date("Y-m-d H:i:s", $timestampInSeconds);

四、将时间字符串转换为时间戳

php 复制代码
// 假设有个日期时间字符串
$dateTimeString = "2024-04-09 15:30:00";

// 使用 strtotime 函数将其转换为时间戳(秒级)
$timestampInSeconds = strtotime($dateTimeString);

// 若需要转换为毫秒级时间戳
$timestampInMilliseconds = strtotime($dateTimeString) * 1000;
相关推荐
JaguarJack2 天前
FrankenPHP 原生支持 Windows 了
后端·php·服务端
BingoGo2 天前
FrankenPHP 原生支持 Windows 了
后端·php
JaguarJack3 天前
PHP 的异步编程 该怎么选择
后端·php·服务端
BingoGo3 天前
PHP 的异步编程 该怎么选择
后端·php
JaguarJack4 天前
为什么 PHP 闭包要加 static?
后端·php·服务端
ServBay5 天前
垃圾堆里编码?真的不要怪 PHP 不行
后端·php
用户962377954485 天前
CTF 伪协议
php
BingoGo7 天前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php
JaguarJack7 天前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php·服务端
BingoGo8 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php