-2

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..
    });
1
  • I don't understand what you're asking. What "real data"? Commented Oct 13, 2010 at 18:30

3 Answers 3

3

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;
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

The Unix format timestamp would first need to be multiplied by 1000 to convert it to milliseconds.
My mistake, I thought getTime() returned the time in seconds.
0

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 Problem with date formats in JavaScript with different browsers 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.

Comments

0

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;
  }
}
}
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.