Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Sort using Date format 2020-12-30T02:07:08.500254-05:00

Hi Team,

I am trying to sort the Json array with the date key. the date is in the format 2020-12-30T02:07:08.500254-05:00. When i am using "new Date", it is throwing me error as "Invalid Date". Below is the json which I am trying to sort and the code (note: "start" is string). The "new Date" is failing as it is not able to identify the date.

[
   {
      "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();});
Solved Solved
0 9 2,876
1 ACCEPTED SOLUTION

Not applicable

below javascript will do the work for you.

 var t = '2020-12-30T02:07:08.500254-05:00';
 var t1 = t.substring(0,23);
 var t2 = t.substring(26);
 var t3 = t1 + t2;
 print(t3);
 var  ms = Date.parse(t3);
 print(ms);

View solution in original post

9 REPLIES 9