简体   繁体   中英

Updating Time in Local Storage

I am trying to connect to the server every minute and pass in the variable of the current time, which would be the lastUpdate. On the server side php file, I plan to compare the passed in time variable with a TIMESTAMP in the database rows; much like if (time1-time2 > certain value)... So far the javascript code is:

var time;
var timer_is_on = 0;
localStorage.lastUpdate = 0;
localStorage.numUpdates = 0;

function timedCount()
{
    localStorage.lastUpdate = new Date();
    //connect to server
    contactServer(localStorage.lastUpdate);
    currentCount=currentCount+1;
    time=setTimeout("timedCount()",60000);
}

My question is whether I am doing this correctly. I am declaring localStorage.lastUpdate as new Date() and I'm not sure whether this is correct? I have tried the loop and every minute lastUpdate seems to be the same date and time.

My last question is whether I can actually compare the two time formats from javascript and php. In the SQL timestamp, the format is 2012-03-20 11:14:40 while the date format from the javascript new Date() is Tue Mar 20 2012 12:32:44 GMT-0400 (Eastern Daylight Time) .

Any information would be helpful, thanks!

Be careful when you use time. Your server time may be different from your client time. The best for you is to store the date of the last request in $_SESSION['last']. With this solution, all your problems are not anymore. Your PHP set the date, so it is the same reference, and it's in a good format.

Just keep your timeout on the client side:-)

Use new Date().getTime() to return a UNIX timestamp; that is, the number of seconds since Jan 1st, 1970. This makes it much easier to compare with other times.

localStorage.lastUpdate = new Date().getTime();

Will return something like this: 1332266002.

The PHP equivalent is simply time() .

And to convert that UNIX timestmap into a MySQL TIMESTAMP , use MySQL's FROM_UNIXTIME function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM