localStorageに保存するサンプル

localStorageは保存されていません。

<button id="b">名前・年齢の入力ボタン</button>
<p id="r">localStorageは保存されていません。</p>
const setStorage = (key, value, expire) => {
  let data;
  if (expire !== undefined) {
    data = {
      expire: expire,
      value: value
    };
  } else {
    data = value;
  }
  localStorage.setItem(key, JSON.stringify(data));
}

const getStorage = (key) => {
  let s = localStorage[key];
  if (s === undefined) {
    return undefined;
  }
  s = JSON.parse(s);
  if (new Date(s.expire) > new Date()) {
    return s.value;
  } else {
    localStorage.removeItem(key);
    return undefined;
  }
}

const b = document.getElementById('b');
b.addEventListener('click', () => {
  const n = prompt('Input your name.', '');
  const a = prompt('Input your age.', '');
  const data = {
    name: n,
    age: a
  };
  setStorage('test', data, '2050/01/01 00:00');
  r.textContent = getStorage('test').name + ' ' + getStorage('test').age;
});

if (getStorage('test')) {
  const r = document.getElementById('r');
  r.textContent = getStorage('test').name + ' ' + getStorage('test').age;
}