-1

In JavaScript how do I save a Date object (10 minutes in future) to localStorage, then later check local storage for that date object to see if NOW > dateObject

function getDateObject10MinutesInFuture() {
  return new Date( Date.now() + (1000 * 60 * 10) );
}

function saveDateObjectToLocalStorage(dateObject, key) {
  //what here
}

function isDateObjectExpiredInLocalStorage(key) {
 //what here
}

I think the best solution that I've found is to convert the date object to a string:

const dateInFuture = new Date( Date.now() + (1000 * 60 * 10) );
const dateInFutureStr = date.toString();

// then save the string form in local storage
localStorage.setItem('date', dateInFutureStr);

//then get the string form from local storage on another page or wherever
const checkDateStr = localStorage.getItem('date');
const checkDate = new Date(checkDateStr);

if (new Date() > checkDate) {
    console.log('date expired');
}
Keith Becker
  • 556
  • 1
  • 6
  • 16

3 Answers3

0

You can use the numerical representation of a date, which you can get with Number, .valueOf, .getTime, ... but the unary plus is the shortest:

const toString = dt => +dt+"";
const toDate = s => new Date(+s);

// demo: create some date object
let dt = new Date(Date.now() + 1000);

// convert Date object to string
let s = toString(dt);
// convert string back to Date object
let dt2 = toDate(s);

console.log(dt);
console.log(dt2); // same date

Using these two functions it is easy to use localStorage:

localStorage.setItem('deadline', toString(dt));
// ...
let dt2 = toDate(localStorage.getItem('deadline'));
trincot
  • 317,000
  • 35
  • 244
  • 286
0

You can accomplish this without any actual Date objects (just numbers):

const EXPIRE_TIME_KEY = 'expireTime'
const TEN_MINUTES = 600000 // 1000ms * 60s * 10min

// Time, 10 minutes from now
const tenMinutesLater = Date.now() + TEN_MINUTES

// Save to localStorage (converts to string)
localStorage.setItem(EXPIRE_TIME_KEY, tenMinutesLater)

// ...

// Load from localStorage (convert back to number)
const expireTime = +localStorage.getItem(EXPIRE_TIME_KEY)

// Check if expired
if (Date.now() > expireTime) {
  console.log('Expired')
}
BCDeWitt
  • 4,540
  • 2
  • 21
  • 34
-1
var d1 = new Date (), d2 = new Date ( d1 );
d2.setMinutes ( d1.getMinutes() + 10 );
localStorage.setItem('tenminutesahead', d2);

if(new Date().getTime() > new Date(localStorage.tenminutesahead).getTime()){//code here}
mpora
  • 1,411
  • 5
  • 24
  • 65