【问题标题】:How can I convert UTC time to 12 hr format in javascript?如何在 JavaScript 中将 UTC 时间转换为 12 小时格式?
【发布时间】:2022-07-06 04:21:37
【问题描述】:

所以,基本上我在我的天气预报网站中使用 openweathermap.org api。 但他们提供 UTC 格式的日落。我想要的是将日落的 UTC 格式转换为 12 小时格式。 在这里,我给出了来自 api 的部分 json 响应:

"dt": 1657048911,
"sunrise": 1657066812,
"sunset": 1657114310,
"temp": 23.58,
"feels_like": 24.21,

【问题讨论】:

    标签: javascript api


    【解决方案1】:
    1. 获取 UTC 时间戳
    2. 将其乘以 1000,以毫秒为单位
    3. 将其放入Date 对象中
    4. 使用函数或库格式化日期

    const sunrise = 1657066812; // Load the data from somewhere
    const sunset = 1657114310;
    
    const sunriseDate = new Date(sunrise * 1000);
    const sunsetDate = new Date(sunrise * 1000);
    
    console.log(`The sunrise time is: ${formatAMPM(sunriseDate)} and the sunset time is: ${formatAMPM(sunsetDate)}`);
    
    
    
    
    // Source: https://stackoverflow.com/a/8888498/5771750
    function formatAMPM(date) {
      var hours = date.getHours();
      var minutes = date.getMinutes();
      var ampm = hours >= 12 ? 'pm' : 'am';
      hours = hours % 12;
      hours = hours ? hours : 12; // the hour '0' should be '12'
      minutes = minutes < 10 ? '0'+minutes : minutes;
      var strTime = hours + ':' + minutes + ' ' + ampm;
      return strTime;
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-17
      相关资源
      最近更新 更多