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

如何使用OpenWeatherMap API的timezone字段在原生JS中获取城市当地时间

实现城市对应时区时间展示的修改方案

核心原理

OpenWeatherMap 返回的 timezone 字段为目标城市相对于 UTC 时区的偏移秒数(东时区为正,西时区为负),例如东八区对应值为 28800(即 8 * 3600)。我们只需要基于当前 UTC 时间加上该偏移量,即可得到目标城市的当前时间。

代码修改步骤

1. 新增全局变量存储时区偏移

在 JS 代码最顶部声明变量,用于存储当前查询城市的时区偏移:

let targetTimezoneOffset = 0; // 默认初始为UTC时区

2. API请求成功后更新时区偏移

在拿到接口返回数据后,将时区值赋给上面的全局变量:

const res = await fetch(
  `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${this.apiKey}`
);
const data = await res.json();
if(data.cod === 200) {
  targetTimezoneOffset = data.timezone; // 更新时区偏移
  this.display(data);
} else {
  alert('城市查询失败,请检查输入');
}

3. 改写时间格式化逻辑

修改原有定时器中的时间计算逻辑,使用目标时区的时间计算,同时修复原有代码的两个bug:上午/下午判断逻辑写反、周四拼写错误:

setInterval(() => {
  // 12小时制格式化
  function twelveFormat(hour) {
    if (hour >= 13) {
      return hour % 12;
    } else {
      return hour;
    }
  }
  // 上下午判断,修复原逻辑写反的问题
  function isAM_PM(hour) {
    if (hour >= 12) {
      return "PM";
    } else {
      return "AM";
    }
  }

  const days = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday", // 修复原拼写错误
    "Friday",
    "Saturday"
  ];
  const months = [
    "Jan",
    "Feb",
    "March",
    "Apr",
    "May",
    "Jun",
    "July",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec"
  ];

  // 核心:计算目标城市当前时间
  const targetTimestamp = Date.now() + targetTimezoneOffset * 1000;
  const targetTime = new Date(targetTimestamp);

  // 全部使用UTC方法获取值,避免本地时区干扰
  const date = targetTime.getUTCDate();
  const month = targetTime.getUTCMonth();
  const day = targetTime.getUTCDay();
  const min = String(targetTime.getUTCMinutes()).padStart(2, '0'); // 补前导零,避免出现12:1:5的格式
  const sec = String(targetTime.getUTCSeconds()).padStart(2, '0');
  const hour = targetTime.getUTCHours();
  const hourIn12HR = twelveFormat(hour);
  const ampm = isAM_PM(hour);

  // 渲染时间
  document.querySelector(
    ".content .date-time .time"
  ).innerHTML = `${hourIn12HR}:${min}:${sec} <span id='AM_PM'>${ampm}</span>`;

  // 渲染日期
  document.querySelector(
    ".content .date-time .date"
  ).innerHTML = `${days[day]}, ${date} ${months[month]}`;
}, 1000);

4. 新增搜索触发逻辑

给输入框和搜索按钮绑定触发事件,调用查询接口:

const searchInput = document.querySelector('.search');
const searchBtn = document.querySelector('.myBtn');

// 按钮点击搜索
searchBtn.addEventListener('click', () => {
  const city = searchInput.value.trim();
  if(city) {
    // 调用你的API请求方法即可
  }
})

// 回车搜索
searchInput.addEventListener('keyup', (e) => {
  if(e.key === 'Enter') {
    searchBtn.click();
  }
})

HTML代码(无需修改)

<!-- 时间展示区域 -->
<div class="content">
  <div class="date-time">
    <h1 class="time">
      00:00:00
    </h1>
    <h2 class="date">

    </h2>
  </div>
</div>

<!-- 搜索区域 -->
<div action="" class="myform">
  <input type="" class="search" placeholder="Search">
  <button class="myBtn"><i class="fas fa-search"></i></button>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:54:01