Search code examples
javascriptdatestring-comparisontampermonkey

comparing a date string with current Date()


So, I already have a variable that holds all the cells in a certain column. each cell contains, as it's innerText, a timestamp formatted like such, yyyy-mm-dd hh:mm in 24h format.

How do I go about comparing the string that I have with Date() to see if the string is within the next hour?

I was thinking a for loop to go through the array with an if function inside saying "if the time shown is within an hour of the current time then change the background color of the cell to red.

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

I'm sure there probably needs to be some parse method used or something but I'm not too familiar with it.

note: I'm using Tampermonkey to inject the code into a page I have no control over and so the timestamps are as the come.


Solution

  • Date constructor does the job of parsing for you. So something like this would be all you need:

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

    Explanation:

    Since Javascript Date is based on milliseconds since midnight January 1, 1970, - (minus) operator allows you to treat it as a Number and returns the resulting number as a Number.