FOR THE MODERATORS!!
I CREATED THIS QUESTION ON stackapps AFTER A RESEARCH INTO THE STACK SECTIONS.
DO I NEED TO DELETE THIS ONE?
Hi I’m creating a simple HTML5 app which uses a timeout().
The basic function of the APP is:
you select an Item and a timeout() starts. It works properly but if I close the application the timer will stop of course.
I’m trying to store it in localStorage but it does not work for what I need.
here is my code
get current date
var current = new Date();
check if localStorage is empty or not. If not, it calculate the difference in milliseconds beetwen the stored date and the current date.
function update() {
if (localStorage.time != undefined){
var diff = current - localStorage.time;
alert (diff)
}
update();
here the function save for the date to be stored and it check the difference beetwen the two dates.
function save() {
localStorage.time = new Date();
click_time = localStorage.time;
var diff = click_time - current;
alert (diff);
}
clear the localStorage
function clear() {
localStorage.clear();
}
$(document).ready(function() {
$('input#save').click(function(){
save();
});
$('input#clear').click(function(){
clear();
});
});
<input type="submit" value="click me!" id="save"/>
<input type="submit" value="clear" id="clear"/>
But I just get NaN!!The problem is how do i need to store the date in the localStorage and how can i get it as a date?
Thanks in advance.
Replace all
new Date();withnew Date().getTime();The differences between new Date().getTime()’s will be in milliseconds.
And just to elaborate:
Using new Date() will return a string like this “Fri Mar 30 2012 12:02:33 GMT-0400 (EDT).” So when you try to perform subtraction between two of these strings, you get NaN.
new Date().getTime() will return an integer like this 1333123359919. This is in milliseconds from January 1st, 1970 (or something like that). So the difference between two of these will give you the number of milliseconds between the two calls, which is what you want.