javascript - 将时间戳转换为日期并获取 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);
解决方案
如果您只对时间感兴趣,并且您似乎想要 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));
推荐阅读
- javascript - 在JS中的两个字符串之间查找> 1个字符长度的公共子字符串
- batch-file - 通过批处理文件删除所有不包含“2020”的行
- python - 自定义 DataGenerator - model.fit_generator:TypeError:只有 size-1 数组可以转换为 Python 标量
- r - 如何在R中获得每三个月的第三个星期五
- c# - 无法使用通用身份验证连接到我的树莓派 pi3 模型 B
- javascript - webpackJsonp 改变 chunkHash
- javascript - 使用 document.querySelector 访问 shadow-root 元素
- python - 找到“可见”的 tkinter 框架
- android - android studio 4.0 中无法识别颤振插件
- c# - 如果方法没有返回值,如何验证它是否被调用?