【问题标题】:Sort the date in the format as "2020-12-30T02:07:08.500254-05:00"以“2020-12-30T02:07:08.500254-05:00”的格式对日期进行排序
【发布时间】:2021-01-22 12:09:16
【问题描述】:

在其中一个 json 响应中,我以字符串格式“2020-12-30T02:07:08.500254-05:00”收到这样的日期。现在我的要求是我需要根据日期对 json 进行排序。无法将上述字符串转换为日期格式以使用排序功能。

需要帮助来排序此日期格式。

[
   {
      "id":1,
      "start":"2019-12-30T02:07:08.500254-05:00",
      "subject":"test1",
   },
   {
      "id":2,
      "start":"2020-12-30T02:07:08.500254-05:00",
      "subject":"test2",
   },
   {
      "id":3,
      "start":"2018-12-30T02:07:08.500254-05:00",
      "subject":"test3",
   }
]

我试图对数据进行排序的代码是

db.sort(function(a,b){return new Date(a.start).getTime() - new Date(b.start).getTime();});

【问题讨论】:

  • 什么语言? JSON 本身没有排序功能等。如果是 Java,您应该使用新的OffsetDateTime。顺便说一句,如果所有时间戳都具有相同的偏移量,则无需转换它们,因为它们会根据字符串格式数据正确排序。

标签: json string date


【解决方案1】:

最后我能够自己修复它。这是代码

function db_sort(a, b){
var a = Date.parse(a.start.substring(0,23) + a.start.substring(26));
var b = Date.parse(b.start.substring(0,23) + b.start.substring(26));
return new Date(b).getTime() - new Date(a).getTime();
}

【讨论】:

  • 您忽略了亚毫秒级的数据,这意味着事情可能会出现问题。
猜你喜欢
  • 1970-01-01
  • 2018-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-22
  • 1970-01-01
  • 1970-01-01
  • 2021-07-10
相关资源
最近更新 更多