Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

js如何判断两个时间最接近

我有两个json,一个是实时数据

jsonNow=[
        {'value':'1.77','time':'2020-12-09 14:32:00','name':'A'},
        {'value':'1.77','time':'2020-12-09 14:37:00','name':'B'}
  ]

一个是历史数据,数据比较多,我只截取其中一小部分,格式如下:

jsonHistory = 
[
              {'value':'1.78','time':'2020-12-08 14:31:00','name':'A'},
              {'value':'1.76','time':'2020-12-08 14:35:00','name':'A'},
              {'value':'1.79','time':'2020-12-08 14:36:00','name':'A'},
              {'value':'1.71','time':'2020-12-08 14:31:00','name':'B'},
              {'value':'1.66','time':'2020-12-08 14:35:00','name':'B'},
              {'value':'1.69','time':'2020-12-08 14:36:00','name':'B'}
  ]

现在我想根据jsonNow里的name,找到昨天时间最接近的一条数据,
就像现在,我想找到

[
   {'value':'1.78','time':'2020-12-08 14:31:00','name':'A'},
   {'value':'1.69','time':'2020-12-08 14:36:00','name':'B'}
 ]

我要怎么实现呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

把时间转成时间戳,做减法,哪两个之间的绝对值最小,那他们必然是最接近的。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...