首页 > 解决方案 > 尝试使用特定时区转换 UTC 时间

问题描述

我目前正在通过连接到 OpenWeatherAPI 的 React 创建一个应用程序。该应用程序是当有人在那里输入位置时,它会提取他们特定位置的天气。我遇到的问题是将特定位置的时间戳转换为本地时间。我用过 MomentJs,但时间总是出错。例如,如果有人选择日本东京,我希望它显示日出将是当地时间早上 6:50。现在我要在 2020 年 12 月 28 日星期一 16:50:24 GMT-0500(东部标准时间)回来。

这是 API 片段:

{
  "dt": 1609176171,
    "sys": {
        "type": 1,
        "id": 8074,
        "country": "JP",
        "sunrise": 1609192224,
        "sunset": 1609227369
    },
    "timezone": 32400,
    "id": 1862143,
    "name": "Horinouchi",
    "cod": 200
}

标签: javascriptreactjsapiopenweathermap

解决方案


timezone您可以通过添加值来创建日出日期。

下面的示例将在天气记录 (Horinouchi) 的时区中生成日期和时间,而不是用户的时区。

const data = {
  "dt": 1609176171,
  "sys": {
    "type": 1,
    "id": 8074,
    "country": "JP",
    "sunrise": 1609192224,
    "sunset": 1609227369
  },
  "timezone": 32400,
  "id": 1862143,
  "name": "Horinouchi",
  "cod": 200
};

// extract sunrise and timezone offset in UNIX epoch seconds
const {
  sys: {sunrise},
  timezone
} = data;

// create Date object for sunrise with timezone offset
const srTime = new Date((sunrise+timezone)*1000);

// convert number to a 2-digit string
const twoDigits = (val) => {
  return ('0' + val).slice(-2);
};

const year = srTime.getUTCFullYear();
const month = twoDigits(srTime.getUTCMonth()+1);
const dayOfMonth = twoDigits(srTime.getUTCDate());
const hours = twoDigits(srTime.getUTCHours());
const minutes = twoDigits(srTime.getUTCMinutes());
const seconds = twoDigits(srTime.getUTCSeconds());

console.log(`${year}-${month}-${dayOfMonth} ${hours}:${minutes}:${seconds}`);

请注意,日期将采用 UTC 时间,因此请务必以这种方式向用户显示它(即不要以本地偏移量显示它)。

要显示 UTC 日期,请使用 Date.prototype:


推荐阅读