Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k 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

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
...