首页 > 解决方案 > 将时间戳转换为日期并获取 HH:MM 格式

问题描述

我从 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);

标签: javascriptjsontimestampweather-api

解决方案


如果您只对时间感兴趣,并且您似乎想要 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));


推荐阅读