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,259
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

Not applicable

The format you will see in Apigee is not as it is in your json. I would suggest to use javascript and format the date properly to a supported format and use.

thank you so much Priyadarshi. Is there way to convert the format in Javascript?

Priyadarshi, thanks for sharing the links. But "moment" did not work as the key word not found and i cannot install any tools at my environment. Also, "new Date" is not working at all and that was my problem from start

Not applicable

in a javascript try the below.

var ms = Date.parse('2020-12-30T02:07:08.500-05:00'); 
print(ms);

I had to do the 2020-12-30T02:07:08.500254-05:00 to the above. you need to limit the second 500254 to 3, you can use javascript to trim that.

You are right. When the secs are trimmed to 3, it is working with "Date.parse". But unfortunately the response is coming for another application which cannot be edited. Is there a way to trim the secs alone with out modifying the remaining date format?

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);

It worked like a charm. Thank you so much Priyadarshi. Here is the code which I have used

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();
}

This works - parsing a date by truncating the string from microseconds to milliseconds.

AND, If the time offset is always the same, the string itself is sortable. You don't need to parse it to a date.

But better to be safe and parse the date.