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

如何使用OpenWeatherMap返回的接口数据通过PHP获取对应地区当地时间

实现逻辑

OpenWeatherMap 接口返回的timezone字段为目标地区相对于UTC时间的偏移秒数,你提供的样例中7200即代表UTC+2时区,直接基于该偏移量计算即可得到当地时间,不需要额外引入国家/地区时区数据库。

具体PHP实现步骤
  • 第一步:解析接口返回的JSON数据,提取timezone字段值
  • 第二步:通过PHP内置时间处理方法叠加偏移量,得到目标地区当地时间

代码示例

// 示例:接口返回的完整JSON字符串(你需要替换为实际接口返回值)
$apiResponseStr = '{"sys":{"type":2,"id":2008110,"country":"CH","sunrise":1633585192,"sunset":1633626144},"timezone":7200}';

// 解析JSON为关联数组
$weatherData = json_decode($apiResponseStr, true);
// 提取时区偏移秒数
$offsetSeconds = $weatherData['timezone'];

// 方法1:基于DateTime类实现(*推荐*,适合需要后续时间操作的场景,避免时间计算误差)
$utcDate = new DateTime('now', new DateTimeZone('UTC'));
$utcDate->modify("+{$offsetSeconds} seconds");
// 按需求自定义时间格式化规则
$localCurrentTime = $utcDate->format('Y-m-d H:i:s');
echo "当地当前时间:" . $localCurrentTime . PHP_EOL;

// 方法2:快捷时间戳计算(适合简单输出场景)
$localCurrentTime2 = date('Y-m-d H:i:s', time() + $offsetSeconds);
echo "当地当前时间:" . $localCurrentTime2 . PHP_EOL;

// 扩展:将接口返回的日出/日落时间转成当地时间
$sunriseLocal = date('H:i:s', $weatherData['sys']['sunrise'] + $offsetSeconds);
$sunsetLocal = date('H:i:s', $weatherData['sys']['sunset'] + $offsetSeconds);
echo "当地日出时间:" . $sunriseLocal . PHP_EOL;
echo "当地日落时间:" . $sunsetLocal . PHP_EOL;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 11:36:04