javascript - 尝试使用特定时区转换 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
}
解决方案
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:
推荐阅读
- php - 出现新警告:include():当我将 PHP 文件上的 WordPress 主题更改为调用高级自定义字段管理样式时,文件名不能为空
- java - 如何从服务帐户密钥文件创建凭据?
- node.js - 无法在 Apple M1 air 上构建节点 rdkafka
- python - 如何在 Python Kivy 中设置 UI 主题图像?
- java - 时间总和不等于模拟的持续时间
- c# - Blazor WASM Net 6 Preview 4 Azure AD - 尝试登录时出错:'无法读取未定义的属性'toLowerCase'
- nginx - 没有从入口控制器获取源 IP
- python - 尝试使用 while 循环从扩展列表派生汇总列表会导致无限循环
- spring-boot - 如何启动和停止春季预定工作?
- javascript - 无法从函数中获取值