JavaScript cross-browser date comparison?
I'm trying to keep in local storage with jQuery plugin jStorage some chunk of HTML and also date and time when that chunk is inserted in local storage, so based on time comparation, if 5 minutes passed, this will be updated in local storage.
Currently, it is working on all browsers, but not, what a surprise, with IE8 and below. IE returns NaN
.
Could you advice me how to store date and compare it with current time - 5 minutes to be cross-browser? Maybe with miliseconds, or some time format that is recognized with all browsers?
Here is the code:
$(document).ready(function() {
var side_user_cp = $.jStorage.get("side_user_cp");
var latest_update = new Date($.jStorage.get("latest_update")); // Here is where I get NaN with IE
var now_date = new Date();
if(!side_user_cp || !latest_update){ // If browser doesn't support local storage, or it first time visit, load it with AJAX
$.get('/ajax/side_user_cp/', function(data) {
$.jStorage.set("latest_update",now_date);
$.jStorage.set("side_user_cp",data);
$('#side').prepend(data);
});
}
else // Browser has support, so check should it be loaded with with AJAX or from Local storage
{
var check_date = new Date(now_date);
check_date.setMinutes(check_date.getMinutes()-5);
if(check_date > latest_update) // latest_update from Loacal storage is here NaN
{
$.get('/ajax/side_user_cp/', function(data) {
$.jStorage.set("latest_update",now_date);
$开发者_开发问答.jStorage.set("side_user_cp",data);
$('#side').prepend(data);
});
}
else
{
$('#side').prepend(side_user_cp);
}
});
You're storing a "Date" instance, and then passing it back in to the Date constructor. That's probably not what you want to do.
You could store the raw numeric timestamp:
$.jStorage.set("latest_update", now_date.getTime());
Then it'd make sense to pass that to construct a new Date later.
(Note that this is a guess; I'm trying to figure out whether IE8 will be confused as you describe if the Date constructor is passed a Date, but jsfiddle appears to have issues at the moment :/ )
edit — nope - bogus. ... edit again but apparently this was helpful (??). When I said it was "bogus", what I meant was that IE seemed to be OK with instantiating a Date from another Date. Possibly however the issue was that Date objects can't be successfully stored in local storage?
精彩评论