views:

93

answers:

3

On my page I'm making ajax-request to get data from server. The data is list of JSON objects..

Every object has name, description and datetime. How can I get the object which is the closer to my real data in browser...

Example:

$(json).each(
    function(i) {
         alert(json.datetime)
        //here have to be some algorithm to comparing the time with my current time instead of alert..
    });
+3  A: 

It sounds like you simply need to loop over each element and compare the date times, storing the current element if it's closer than the last element you compared.

This assumes your json array contains at least one element, and that your datetime fields are standard Unix timestamps.

var closest = json[0];
var current = Date.getTime() / 1000; // current datetime, in seconds since epoch

// start at the 2nd element
for (i = 1; i < json.length; ++i) {
  if (current - json[i].datetime < current - closest.datetime) {
    closest = current;
  }
}
meagar
The Unix format timestamp would first need to be multiplied by 1000 to convert it to milliseconds.
idealmachine
My mistake, I thought `getTime()` returned the time in seconds.
meagar
A: 

Quite often, the UTC timestamps returned through JSON queries are in an ISO 8601 format (e.g. as returned by the JSON interface to the MediaWiki software that powers Wikipedia). Before performing date arithmetic, you will need to convert that to a format that the web browser will recognize.

(See http://stackoverflow.com/questions/3566125/problem-with-date-formats-in-javascript-with-different-browsers/3567007#3567007 for how to do this using regular expressions.)

Then you will need to subtract that time (new Date(timeString.replace(...)...)) from the current time (new Date()). That will give you the interval between the two times in milliseconds (1 second = 1000 milliseconds).

Be aware that this is affected by the accuracy of the client computer's system clock, which you have no control over if you are operating a public web site. If this is the case, you should compare times on your server or at least allow your server to send the accurate time to the client over JSON.

idealmachine
A: 

There is my version made from meagar's Answer... Thanks a lot!!!

$(json).each( function(i) {    
if (Math.abs(cur_time - time) < Math.abs(cur_time - closest)) {
      closest = time;
      current_pk=pk;
  }
}
}
);
Pol