Hec46
Hec46

Reputation: 191

Javascript - getTime() not working

I am making a little quiz in html with 10 questions, each one in a separate html pages. At the point the user presses the START button in the index.html, I do the following:

var s = new Date();
sessionStorage.start_test = s;

and when he presses the FINISH button in page 10 of the quiz, I do:

var e = new Date();
sessionStorage.finish_test = e;

Finally, I have a page where the grade is displayed, and also the time spent in answering the quiz, with the following:

var start = sessionStorage.getItem( "start_test" );
var fin = sessionStorage.getItem( "finish_test" );
var time = fin.getTime() - start.getTime();
alert( time );

But this does not seem to work, as it is not displaying the javascript alert box, and in the console I get the following error:

Uncaught TypeError: Object Wed Jul 09 2014 13:38:06 GMT+0200 has no method 'getTime'

What am I doing wrong? Any help will be very much appreciated!

Upvotes: 2

Views: 4112

Answers (2)

user2226755
user2226755

Reputation: 13159

sessionStorage is string, not Date() instance.

var start = new Date(sessionStorage.getItem( "start_test" ));
var fin = new Date(sessionStorage.getItem( "finish_test" ));
var time = fin.getTime() - start.getTime();
alert( time );

Upvotes: 1

Vlas Bashynskyi
Vlas Bashynskyi

Reputation: 2014

When you add a Date object to local or session storage, it gets serialized into string, so, when you retrieve it with getItem() you get a string. To convert it back to Date object pass this string to Date() constructor:

var myDate = new Date( localStorage.getItem( 'foobardate' ) );

Upvotes: 3

Related Questions