将本地时间从 openweather Api 转换为长格式

问题描述 投票:0回答:1

我从开放天气API获取数据

dt:1679888142
timezone:7200

我正在尝试通过在 JavaScript 中应用

Date
对象然后使用
toUTCString()
来获取当地时间,从而将 UNIX 时间更改为本地时间。

目标是将获取的本地时间

'Mon, 27 Mar 2023 05:35:42 GMT'
变成长格式时间eg
'Monday, March 27 at 4:35 AM'
。当我应用以下代码时,它没有格式化也添加了我的时区差异

这是下面的代码

  let epochtime = weatherData.dt;
  let timezone = weatherData.timezone;
  const rfc2822Date = new Date((epochtime + timezone) * 1000).toUTCString();

  const options = {
    weekday: "long",
    month: "long",
    day: "numeric",
    hour: "numeric",
    minute: "numeric",
    hour12: true
  };
const longFormatDateTime =  rfc2822Date.toLocaleString("en-us",options);

我试图再次将日期传递给日期对象,这将导致 gmt+timezone 和格式。格式化似乎有效,但本地时间错误

javascript unix-timestamp openweathermap
1个回答
0
投票

您需要直接在日期对象而不是 rfc2822 字符串上调用

toLocaleString
。我建议这样实现它

  let epochtime = weatherData.dt;
  let timezone = weatherData.timezone;
  const UNIXDate = new Date((epochtime + timezone) * 1000);

  const options = {
    weekday: "long",
    month: "long",
    day: "numeric",
    hour: "numeric",
    minute: "numeric",
    hour12: true
  };

const longFormatDateTime =  UNIXDate.toLocaleString("en-us",options);

希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.