将日期字符串与当前日期()进行比较



所以,我已经有了一个变量,它保存了某一列中的所有单元格。每个单元格都包含一个时间戳,其格式类似于24小时格式的yyyy-mm-dd-hh:mm。

如何将我的字符串与Date((进行比较,以查看该字符串是否在下一个小时内?

我在想一个for循环来遍历数组,里面有一个if函数,说"如果显示的时间在当前时间的一小时内,那么将单元格的背景色更改为红色。">

for(var i=0; i<column.length;i++){
if(column[i].innerText - Date() < 1hr){   //this line needs work
column[i].style.backgroundColor='#ff000';
} else(){
}
};

我确信可能需要使用一些解析方法或其他东西,但我不太熟悉

注意:我正在使用Tampermonkey将代码注入到一个我无法控制的页面中,因此时间戳是随机的。

日期构造函数为您完成解析工作。所以你只需要这样的东西:
hour = 3600000 //1 hour in ms
nextHour = new Date(column[i].innerText) - new Date()
if(nextHour <= hour && nextHour >= 0) {
//Your code here
}

说明:

由于Javascript Date是基于1970年1月1日午夜以来的毫秒数,因此-(minus(运算符允许您将其视为数字,并将生成的数字返回为数字。

更改此项:

if(column[i].innerText - Date() < 1hr){

对此:

var hourNow = new Date().getHours();
var hourColumn = Number(column[].innerText.split("")[11] + "" + column[].innerText.split("")[12]);
if (hourNow + 1 >= hourColumn || hourColumn + 1 <= hourNow) {

它应该起作用。

您可以使用以下方法。这里我使用了getUTCHours(),因为new Date(new Date(columns[i].innerText) - new Date())会给出UTC时间戳。你可以在这里找到关于UTC时间戳的解释

var columns;
function changecolors() {
columns = document.getElementsByClassName('column');
for (var i = 0; i < columns.length; i++) {
if (new Date(new Date(columns[i].innerText) - new Date()).getUTCHours() < 1) {
columns[i].style.backgroundColor = '#ff0000';
}
};
}
<div class="column">2018-11-18 09:30</div>
<div class="column">2018-11-18 11:00</div>
<button onclick="changecolors()">Change Colors</button>

最新更新