当我在下拉列表中选择“过去 24 小时”时,我有一个下拉列表(值为“过去 24 小时”、“过去 48 小时”等) 我需要从现在到昨天的所有日期,间隔一小时。
我试过了,
var todayDate = new Date();
if(type=="hours"){ // for hours based drop-down
var oneDayAgo = new Date(todayDate.getTime());
oneDayAgo.setDate(todayDate.getDate() - 1);
console.log("oneDayAgo"+oneDayAgo);
var hours = todayDate.getHours();
for(var i = hours; i <= hours+24; i++) {
if(i<25){
var newHours=i;
var newDates=todayDate.getFullYear() + "-" + ("00" + (todayDate.getMonth() + 1)).slice(-2) + "-" + ("00" + todayDate.getDate()).slice(-2) + " " + ("00" +newHours).slice(-2) + ":" + ("00" + todayDate.getMinutes()).slice(-2) + ":" + ("00" + todayDate.getSeconds()).slice(-2);
console.log(newDates);
}else{
var newHours=i-24;
var newDates=oneDayAgo.getFullYear() + "-" + ("00" + (oneDayAgo.getMonth() + 1)).slice(-2) + "-" + ("00" + oneDayAgo.getDate()).slice(-2) + " " + ("00" +newHours).slice(-2) + ":" + ("00" + oneDayAgo.getMinutes()).slice(-2) + ":" + ("00" + oneDayAgo.getSeconds()).slice(-2);
console.log(newDates);
}
}
}
我的预期输出是,
例如当前日期和时间是 2014-04-27 13:07 意味着,
输出如 2014-04-27 13:07、2014-04-27 12:07、2014-04-27 11:07、2014-04-27 10:07.... 2014-04-26 13 :07
请帮忙解决这个问题。谢谢
最佳答案
function getDateItems(hours) {
var toDate = new Date();
var fromDate = new Date();
fromDate.setTime(fromDate.getTime() - (hours * 60 * 60 * 1000));
var result = [];
while (toDate >= fromDate) {
result.push(toDate.getFullYear() + "-" + ("00" + (toDate.getMonth() + 1)).slice(-2) + "-" + ("00" + toDate.getDate()).slice(-2) + " " + ("00" + toDate.getHours()).slice(-2) + ":" + ("00" + toDate.getMinutes()).slice(-2) + ":" + ("00" + toDate.getSeconds()).slice(-2));
// consider using moment.js library to format date
toDate.setTime(toDate.getTime() - (1 * 60 * 60 * 1000));
}
return result;
}
var datesFrom24Hours = getDateItems(24);
var datesFrom48Hours = getDateItems(48);
console.log(datesFrom24Hours);
关于javascript - 在 javascript 中获取循环的 24 小时日期和时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43651552/