0

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?

Mask
  • 573
  • 7
  • 24
  • Use https://momentjs.com - they have functions. You would do it like this: `moment(new Date(X)).diff(moment(new Date(Y), 'hours')` and then you would check the 48. You could also check for 2 days. You can also check isBetween, isAfter or isBefore and much more. – Stefan Rein Jul 16 '20 at 06:12
  • Does this answer your question? [Check time difference in Javascript](https://stackoverflow.com/questions/1787939/check-time-difference-in-javascript). Also [this](https://stackoverflow.com/questions/18623783/get-the-time-difference-between-two-datetimes). And [this](https://stackoverflow.com/questions/3224834/get-difference-between-2-dates-in-javascript/3224854#3224854). And [this](https://stackoverflow.com/questions/13894632/get-time-difference-between-two-dates-in-seconds). And [this](https://stackoverflow.com/questions/1036742/date-difference-in-javascript-ignoring-time-of-day) – Oleg Valter is with Ukraine Jul 16 '20 at 06:14
  • Also be aware of that `getTime()` will come at in `milliseconds` not hours. – Stefan Rein Jul 16 '20 at 06:15
  • You need `48 hours` = `48 * 60 * 60 * 1000 milliseconds`. Use `x.getTime()-(item[7]).getTime() > 48 * 60 * 60 * 1000`. – Karan Jul 16 '20 at 06:22

1 Answers1

4

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
AKT
  • 942
  • 6
  • 16
  • 1
    `new Date() - new Date(item[7])` will return difference in `milliseconds` so you can `omit` `.getTime()`. – Karan Jul 16 '20 at 06:26
  • @Karan Oh yeah, we don't need that. – AKT Jul 16 '20 at 06:30
  • thanks for all the wisdom you shared and the answer explains a lot. just one question what is `36e5` here – Mask Jul 16 '20 at 06:31
  • 1
    Since the difference is in milliseconds and one hour has 3600000 milliseconds, 36e5 is the [scientific notation](https://stackoverflow.com/questions/27151311/how-to-use-scientific-notation-in-js) of the number. You can also use 3600000, but I am sure you won't ,after this. – AKT Jul 16 '20 at 06:36