1

I am trying to check if a timestamp I have in local storage is more than 6 hours old, I don't believe my logic is correct. Here is what I have so far.

function checkBasket() {
  const basket = localStorage.getItem('user_basket');

  if (basket) {
    var sixHours = 5 * 60 * 60 * 1000;

    return ((new Date) - JSON.parse(basket).timestamp) < sixHours;
  }

  return false;
}

So I am trying to get this function to return true if the localstorage basket.timestamp is less than 6 hours old, otherwise false.

ajmajmajma
  • 13,712
  • 24
  • 79
  • 133

2 Answers2

3

var date1 = new Date("Mon Oct 24 2016 04:22:12 GMT+0530 (IST)");
var date2 = new Date("Mon Oct 24 2016 10:22:12 GMT+0530 (IST)");
var hours = Math.floor(Math.abs(date1 - date2) / 36e5);
console.log(hours);

You Can Make Use Of This Code Snippet

Reference: How to get the hours difference between two date objects?

Community
  • 1
  • 1
Shankar Shastri
  • 1,134
  • 11
  • 18
2
var diffHours = Math.abs(date1 - date2) / 36e5

The subtraction returns the difference between the two dates in milliseconds. 36e5 is the scientific notation for 60*60*1000, dividing by which converts the milliseconds difference into hours

  • OK, so what's wrong with the OP's code? (Other than that they're using 5 hours rather than 6?) – nnnnnn Oct 24 '16 at 03:23