将时间戳转换为日期并获取HH:MM格式

问题描述 投票:-1回答:2

我从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
2个回答
1
投票

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

-2
投票

尝试moment.js

它提供了许多日期实用程序,格式化变得非常容易。


-1
投票

使用toLocaleTimeString()

var s = new Date().toLocaleTimeString("en-US").substr(0,5)
console.log(s)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

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