Saving and loading dates
Save your datetime always in UTC ISO and load it to the user interface using local ISO. Use native widgets to avoid facing date format preferences (middle endian, little endian, etc)
by Génesis García Morilla
September 28, 2017
HTML
<input type="datetime-local">
<button>Reset</button>
<button>Save</button>
<button>Load</button>
JavaScript
$input = document.querySelector('input')
// Reset
document.querySelector('button:nth-of-type(1)').onclick = () =>
$input.value = ''
// Save (UTC ISO)
document.querySelector('button:nth-of-type(2)').onclick = () =>
localStorage.setItem('datetime', $input.value &&
new Date($input.value).toISOString())
// Load (Local ISO)
document.querySelector('button:nth-of-type(3)').onclick = () =>
$input.value = localStorage.getItem('datetime') &&
toLocalISOString(new Date(localStorage.getItem('datetime'))).slice(0, -8)
function toLocalISOString(d) {
const offset = d.getTimezoneOffset()
return new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
d.getHours(),
d.getMinutes() - offset,
d.getSeconds(),
d.getMilliseconds()).toISOString()
}