You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

咨询C#中DateTimeOffset.Now在PHP中的等效实现及时间戳获取方法

PHP 实现 C# DateTimeOffset.Now 等效功能(获取Unix时间戳)

C# 中 DateTimeOffset.Now.ToUnixTimeSeconds() 返回的是UTC时间1970-01-01 00:00:00到当前时间的秒级Unix时间戳(类似1660991390),PHP 里可以通过以下方式实现完全等效的功能:

直接获取秒级时间戳

最简便的方法是使用 time() 函数,它直接返回当前UTC时间对应的秒级Unix时间戳,和C#的结果完全一致:

$timestamp = time();
echo $timestamp; // 输出示例:1660991390

先构造带时区的时间对象再转时间戳

如果需要先得到类似 DateTimeOffset 包含本地时区信息的时间对象,再转换为时间戳,可以使用 DateTime 类:

// 创建带本地时区的当前时间对象
$localDateTime = new DateTime('now', new DateTimeZone(date_default_timezone_get()));
// 转换为秒级Unix时间戳
$timestamp = $localDateTime->getTimestamp();
echo $timestamp;

毫秒级时间戳(可选)

如果需要对应C#的 DateTimeOffset.Now.ToUnixTimeMilliseconds(),可以用以下代码获取毫秒级时间戳:

$timestampMs = round(microtime(true) * 1000);
echo $timestampMs; // 输出示例:1660991390123

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 07:36:19