Search code examples
javascriptdate-difference

Check if time difference is more than 48 hours


I have two times one captured from google sheet item[7] and another from new date() method.

Now I want to check if the time difference is more than 48 hours and filter the data accordingly.

Here is my complete code :

function leavetat() {
  
  var ss = SpreadsheetApp.openById('1KtxxxxxxxxxxxxxxxxxxxxxxxPMc');

  var sheet2 = ss.getSheetByName("Temp Sheet");
  var data = sheet2.getDataRange().getValues();
  
  var x = new Date();
  
  let datax = data.filter(function(item){x.getTime()-(item[7]).getTime() >= 48 })
  
  Logger.log(datax)
  
}

However, this is not working :

x.getTime()-(item[7]).getTime() > 48

what is the resolution?


Solution

  • Most likely because item[7] is not a date object. Try converting it to a Date object.

    new Date(item[7]).getTime()
    

    Also it is in milliseconds not hours.

    If you have two date objects then you can use

    //(Math.abs(firstDate - secondDate) / 36e5) >= 48
    (Math.abs(new Date() - new Date(item[7])) / 36e5) >= 48