[英]Trying to convert UTC time with specific time zones
I am currently creating an app through React which connects to the OpenWeatherAPI.我目前正在通过连接到 OpenWeatherAPI 的 React 创建一个应用程序。 The app is when someone types in there location it pulls the weather of their specific location.
该应用程序是当有人在那里输入位置时,它会提取他们特定位置的天气。 The issue I am having is converting the timestamp of the specific location to a local time.
我遇到的问题是将特定位置的时间戳转换为本地时间。 I have used MomentJs, but the time keeps up coming wrong.
我用过 MomentJs,但时间总是出错。 The issue for example if someone chooses Tokyo, Japan I want it to show that the sunrise will be 6:50 am their local time.
例如,如果有人选择日本东京,我希望它显示日出将是当地时间早上 6:50。 Right now I am getting back Mon Dec 28 2020 16:50:24 GMT-0500 (Eastern Standard Time).
现在我要在 2020 年 12 月 28 日星期一 16:50:24 GMT-0500(东部标准时间)回来。
This is the API snippet:这是 API 片段:
{
"dt": 1609176171,
"sys": {
"type": 1,
"id": 8074,
"country": "JP",
"sunrise": 1609192224,
"sunset": 1609227369
},
"timezone": 32400,
"id": 1862143,
"name": "Horinouchi",
"cod": 200
}
You can create a date for the sunrise by adding the timezone
value.您可以通过添加
timezone
值来创建日出日期。
The example below will produce a date and time in the timezone of the weather record (Horinouchi), NOT the timezone of the user.下面的示例将在天气记录 (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}`);
Note that the date will be in UTC time, so be sure to display it for the user that way (ie don't display it with a local offset).请注意,日期将采用 UTC 时间,因此请务必以这种方式向用户显示它(即不要以本地偏移量显示它)。
To display the UTC date, use Date.prototype:要显示 UTC 日期,请使用 Date.prototype:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.