简体   繁体   中英

Comparing Timestamps in PHP/Javascript

I'm developing a web based app that checks for updates on the server and notifies the user if there are any. This is an alternative to the push method; the background process in the app checks the PHP file every hour to see if there are new additions to the MySQL database. If there are it notifies the user on the home screen.

The part I am having trouble is comparing timestamps. I keep the "lastUpdate" variable which tells the last time the phone accessed the PHP file in local storage in the JavaScript file. Every time the phone connects it passes the variable to when it last connected, if there are any new entries in the database with timestamps greater than that of the last update the notification count will be increased.

PHP:

$lastUpdate = $_GET["q"];
//connect to server

mysql_select_db("dbr", $con);
$sql="SELECT * FROM notification";
$result = mysql_query($sql);

$updateCount = 0;
if ($lastUpdate == "1970-01-01 01:00:00")
{  $compareTime = time();}
else
{  $compareTime = intval($lastUpdate); }

while($row = mysql_fetch_array($result))
{
    $rowTime = strtotime($row['timeAdded']);
    if ($rowTime >= $compareTime) 
    {   
        $updateCount++;
    }
}
echo json_encode( array('lastUpdate' => $compareTime, 'numUpdates' => $updateCount,     'passedValue' => $compareTime) );

JavaScript:

var timedLoop;
var timer_is_on=0;
localStorage.lastUpdate = "1970-01-01 01:00:00";
localStorage.numUpdates = 0;
localStorage.passedValue = ""; //used it for debugging

function timedCount()
{
    document.getElementById('testContent').innerHTML = "lastUpdate: " + localStorage.lastUpdate;
    document.getElementById('testContent2').innerHTML = "numUpdates: " + localStorage.numUpdates;
    document.getElementById('testContent3').innerHTML = "passedValue: " + localStorage.passedValue;

    contactServer(localStorage.lastUpdate);
    if(Number(localStorage.numUpdates)>0)
    {       
        alert("NOTIFICATIONS AVAILABLE");
        notifyUser();
        localStorage.numUpdates = 0;
    }
    document.getElementById('txt').value=new Date();
    timedLoop=setTimeout("timedCount()",10000);
}

function contactServer(update)
{
    if (window.XMLHttpRequest){ xmlhttp=new XMLHttpRequest();}
    else{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}

    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            var result = JSON.parse(xmlhttp.responseText);
            localStorage["lastUpdate"] = result["lastUpdate"];
            localStorage["numUpdates"] = result["numUpdates"];
            localStorage["passedValue"] = result["passedValue"];
        }
    }
    xmlhttp.open("GET","address.php?q="+update,true);
    xmlhttp.send();
}

Problem is it is not working for me. I'm fairly new to this so I'm not sure if I'm doing it correctly. The function timedCount() is loaded in the body by "onload" so it runs at the start and keeps running every 10 seconds in this case. But the timestamp values stop changing after the first two loops. If I try to change the code a bit I get completely unexpected results. I've been at this for a while so any help would be appreciated!

1) You start with localStorage.lastUpdate = "1970-01-01 01:00:00"; and send that value to the server as a GET parameter named q .

2) The first time this matches your if statement and $compareTime = time(); is executed. This value, the current timestamp, is the returned to the JavaScript as the lastUpdate JSON property.

3) In JavaScript you pick this value up and run localStorage["lastUpdate"] = result["lastUpdate"]; to save it. Ten seconds passes and you make another request, now with the previous timestamp as the q parameter.

4) Your PHP's else statments kicks in and assigns the given -- previous -- timestamp to the `$compareTime variable. Thus you use the very same data once again for the following while loop.

Simply returning 'lastUpdate' => time() instead in that json_encode() would do the trick. Else it would continue to request the same time over and over.

However I am curious about how you mix the formats. time() gives an actual timestmap like 1335048166, which is a totally different format from "1970-01-01 01:00:00". If you have timestamps also in the database I suggest sticking with that one format throughout your application.

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