【问题标题】:Convert timestamp to date and get HH:MM format将时间戳转换为日期并获取 HH:MM 格式
【发布时间】:2020-01-25 05:11:29
【问题描述】:

我从 DarkShy 天气 api 接收 JSON 对象,我想访问 Chart.JS 图表的每个报告的时间戳,我将在其中显示一天的温度,现在我被困在转换时间戳转换成 HH:DD:SS 格式。

这是我尝试过的

// Displays the wrong time according to https://www.epochconverter.com/
var timeofDay = new Date(daily[i].time)
time.push( timeofDay.toTimeString().split(' ')[0] )

// Gets rid off the time, tho It get the date correctly
var timeofDay = new Date(parseFloat(daily[i].time) * 1000)
time.push( timeofDay )

// Returns the wrong date and time
time.push(new Date(daily[i]))

以下是我循环遍历 JSON 文件的方式

let time = []
let temperatureDaily = []

for(var i=0; i<daily.length; i++){
 // Push the values into the arrays
 var timeofDay = new Date(parseFloat(daily[i].time) * 1000)
                        time.push( timeofDay )

 temperatureDaily.push( (parseFloat(daily[i].temperatureHigh) + parseFloat(daily[i].temperatureLow)) /2)
}
console.log(time);

【问题讨论】:

标签: javascript json timestamp weather-api


【解决方案1】:

试试moment.js

它提供了很多日期实用程序,格式化变得超级简单。

【讨论】:

    【解决方案2】:

    如果您只对时间感兴趣,并且您似乎想要 UTC,请使用 UTC 方法来格式化时间。或者您可以使用 toISOString 并修剪不需要的位,例如

    let timeValue = 1569304800;
    let d = new Date(timeValue * 1000);
    
    // Use toISOString
    let hms = d.toISOString().substr(11,8);
    console.log(hms);
    
    // Manual format
    function toHMS(date){
      let z = n => ('0'+n).slice(-2);
      return `${z(d.getUTCHours())}:${z(d.getUTCMinutes())}:${z(d.getUTCSeconds())}`
    }
    console.log(toHMS(d));

    【讨论】:

      猜你喜欢
      • 2016-11-26
      • 2019-02-25
      • 1970-01-01
      • 2018-02-05
      • 2015-08-19
      • 2020-02-23
      • 1970-01-01
      • 2011-03-05
      相关资源
      最近更新 更多