0

I'm a bit of a newbie so please bear with me. I've created a date object in javascript every time someone opens a new page. I want to save the time the user opened the page and create another date object exactly one day later to create a countdown timer showing time elapsed from date 1 to date 2.

To accomplish this, I tried subtracting the two dates using .getTime; I want to keep the second date static instead of one day ahead of the current time. Unfortunately, this is not happening even though I have confined d2 (Date 2) to a condition that only runs once and is stored in variable nextday. Here's my JS

$(function (){
localStorage.clear()
var ran = JSON.parse(localStorage.getItem('run'))
d1 = new Date()
var i = 0 

if(!ran){
    i+=1
    d2 = new Date(d1)
    nextday = d2.setHours(d1.getHours()+24)
    console.log(i)
    console.log(typeof(nextday))
    localStorage.setItem('run',JSON.stringify('ran'))
    localStorage.setItem('nextday',JSON.stringify(nextday))
}
console.log(localStorage)
nday = JSON.parse(localStorage.getItem('nextday'))
console.log(nday)
var seconds = (nday - d1.getTime())

console.log(seconds)
console.log(localStorage)
})
I Like
  • 1,711
  • 2
  • 27
  • 52
  • Turn the object into a function. Every time you call for it, you will get the same data. – Derek Pollard Dec 10 '16 at 01:44
  • Don't add 1 day by adding 24 hours since in a place that observes daylight saving, there are two days every year that are not 24 hours long. Add one to the date, see [*Add +1 to current date*](http://stackoverflow.com/questions/9989382/add-1-to-current-date/9989458#9989458). – RobG Dec 11 '16 at 13:00

2 Answers2

1

Your script is clearing local storage every time the page is loaded:

localStorage.clear()

This will prevent anything from being stored across runs. Remove it.

1

You're clearing your localStorage before you access your locally-stored data. Thus, your ran variable is always empty. Remove that one call to clear(), and everything should work fine.

$(function() {
  // localStorage.clear() <= the offending code!
  var ran = JSON.parse(localStorage.getItem('run'))
  d1 = new Date()
  var i = 0

  if (!ran) {
    i += 1
    d2 = new Date(d1)
    nextday = d2.setHours(d1.getHours() + 24)
    console.log(i)
    console.log(typeof(nextday))
    localStorage.setItem('run', JSON.stringify('ran'))
    localStorage.setItem('nextday', JSON.stringify(nextday))
  }
  console.log(localStorage)
  nday = JSON.parse(localStorage.getItem('nextday'))
  console.log(nday)
  var seconds = (nday - d1.getTime())

  console.log(seconds)
  console.log(localStorage)
})
gyre
  • 16,369
  • 3
  • 37
  • 47