Skip to content
Advertisement

Sort String Json Date

I am getting date values like that: "/Date(1560458281000)/" from an array of objects. I just want to order these dates by descending and ascending. I am open to any examples with pure JavaScript and/or moment.js By the way, hours and minutes are important. I will show it like 2014/10/29 4:50

let dateSorted = this.props.myObj.sort(function(a,b) {
  sorted= new Date(Number(a.Date.replace(/D/g, ''))) - new 
  Date(Number(b.Date.replace(/D/g, '')))
  return sorted;
})

This code doesn’t work.

Advertisement

Answer

You should be carefull with your sorted variable, it’s missing the const / let initializer, I would have written:

let dateSorted = this.props.differences.sort(function(a,b) {
  const timeA = Number(a.Date.replace(/D/g, ''))
  const timeB = Number(b.Date.replace(/D/g, ''))

  return timeA - timeB;
})

And since your dates are in timestamp format you don’t even need to convert them to date to compare them, you can substract the numbers dicrectly.

A simpler way would be to use localeCompare:

let dateSorted = this.props.differences.sort(function (a, b) {
  return a.Date.localeCompare(b.Date)
})

Since your date would be properly ordered by using the alphabetical order.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement