Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
帮我做算法。。Javascript_Javascript_Jquery_Ajax_Json - Fatal编程技术网

帮我做算法。。Javascript

帮我做算法。。Javascript,javascript,jquery,ajax,json,Javascript,Jquery,Ajax,Json,在我的页面上,我正在发出ajax请求以从服务器获取数据。数据是JSON对象的列表 每个对象都有名称、描述和日期时间。如何在浏览器中获取与真实数据最接近的对象 例如: $(json).each( function(i) { alert(json.datetime) //here have to be some algorithm to comparing the time with my current time instead of alert..

在我的页面上,我正在发出ajax请求以从服务器获取数据。数据是JSON对象的列表

每个对象都有名称、描述和日期时间。如何在浏览器中获取与真实数据最接近的对象

例如:

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

听起来您只需要循环每个元素并比较日期时间,如果当前元素比您比较的最后一个元素更接近,则存储当前元素

这假定
json
数组至少包含一个元素,并且
datetime
字段是标准的Unix时间戳

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;
  }
}
var=json[0];
var current=Date.getTime()/1000;//当前日期时间,以自历元起的秒为单位
//从第二个元素开始
for(i=1;i
通常,通过JSON查询返回的UTC时间戳采用ISO 8601格式(例如,通过JSON接口返回给支持Wikipedia的MediaWiki软件)。在执行日期算术之前,您需要将其转换为web浏览器可以识别的格式

(有关如何使用正则表达式执行此操作,请参见。)

然后需要从当前时间(
new Date()
)中减去该时间(
new Date(timeString.replace(…)…)
)。这将以毫秒为单位给出两次之间的间隔(1秒=1000毫秒)


请注意,这会受到客户端计算机系统时钟准确性的影响,如果您正在操作公共网站,则无法控制该时钟。如果是这种情况,您应该比较服务器上的时间,或者至少允许服务器通过JSON向客户端发送准确的时间。

我的版本是根据meagar的答案制作的。。。非常感谢

$(json).each( function(i) {    
if (Math.abs(cur_time - time) < Math.abs(cur_time - closest)) {
      closest = time;
      current_pk=pk;
  }
}
}
);
$(json).each(函数(i){
if(Math.abs(cur_-time-time)
我不明白你在问什么。什么是“真实数据”?Unix格式的时间戳首先需要乘以1000才能将其转换为毫秒。我的错误是,
getTime()
以秒为单位返回时间。