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

comparing a date string with current Date()

所以,我已经有了一个变量来保存特定列中的所有单元格。 每个单元格都包含一个时间戳,因为它是 innerText,格式如下,yyyy-mm-dd hh:mm,24 小时格式。

如何将我拥有的字符串与 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 将代码注入我无法控制的页面,因此时间戳即将到来。

改变这个:

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) {

它应该可以工作。

日期构造函数为您完成解析工作。所以像这样的东西就是你所需要的:

hour = 3600000 //1 hour in ms
nextHour = new Date(column[i].innerText) - new Date()
if(nextHour <= hour && nextHour >= 0) {
    //Your code here
}

说明:

由于 Javascript 日期基于自 1970 年 1 月 1 日午夜以来的毫秒数,-(减号)运算符允许您将其视为数字,returns 将结果数字视为数字。

您可以采用以下方法。这里我使用了 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>