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

API返回的DateTime时间戳转换异常,求修正代码生成指定格式

问题原因与修正方案

你得到异常日期02/17/55034的核心原因是:API返回的是毫秒级时间戳(1674542180860),而PHP的DateTime构造器使用@前缀时,要求传入的是秒级时间戳。直接将毫秒数当作秒数使用,会让时间被放大1000倍,导致年份严重偏离正常范围。

修正后的代码(支持January 12th, 2023格式)

if (!empty($data->Data->Shipment->UpdatedOn)):
    // 提取毫秒时间戳与时区偏移
    preg_match('/\/Date\((\d+)([+-]\d{4})\)\//', $data->Data->Shipment->UpdatedOn, $matches);
    $milliseconds = $matches[1];
    $timezoneOffset = $matches[2];
    
    // 转换毫秒为秒级时间戳
    $timestamp = (int)($milliseconds / 1000);
    
    // 创建DateTime对象并设置时区
    $date = new DateTime("@$timestamp");
    $date->setTimezone(new DateTimeZone("Etc/GMT" . substr($timezoneOffset, 0, 1) . substr($timezoneOffset, 1, 2)));
    
    // 获取日期的日部分,生成序数词后缀
    $day = $date->format('j');
    $suffix = match (true) {
        $day % 100 >= 11 && $day % 100 <= 13 => 'th',
        $day % 10 == 1 => 'st',
        $day % 10 == 2 => 'nd',
        $day % 10 == 3 => 'rd',
        default => 'th'
    };
    
    // 拼接目标格式
    $formattedDate = $date->format('F j') . $suffix . ', ' . $date->format('Y');
    
    echo '<span>' . $formattedDate . '</span>';
endif;

关键修正点说明

  • 时间戳转换:将提取到的毫秒数除以1000,转换成PHPDateTime能识别的秒级时间戳。
  • 时区处理:解析API返回的时区偏移(+0000),设置正确的时区,避免时间偏移错误。
  • 序数词生成:通过判断日期的日部分,生成对应的st/nd/rd/th后缀,实现January 12th这类格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 03:55:17