Dawid Kwiatoń
Dawid Kwiatoń

Reputation: 167

How do I change date formatting in Javascript to enable sorting?

I am writing my dates of birth in the following manner:

I wanted to sort it using something similar to this code (enabling sorting by birth):

var obj = [{"id":1,"dateOfBirth":"1.7.1990 11:35"}, 
 {"id":4,"dateOfBirth":"4.02.1976 14:37"},{"id":2,"dateOfBirth":"28.10.1950 
2:15"},{"id":3,"dateOfBirth":"03.01.1963 23:10"}]

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

I am unsure if I need to reformat the dates of birth to achieve this.

Upvotes: 0

Views: 119

Answers (2)

raul.vila
raul.vila

Reputation: 1984

A working version with optional time values.

var obj = [{
    "id": 1,
    "dateOfBirth": "1.7.1990"
  },
  {
    "id": 4,
    "dateOfBirth": "4.02.1976 14:37"
  }, {
    "id": 2,
    "dateOfBirth": "28.10.1950 2:15"
  }
];

console.log(
  obj.sort(function(a, b) {
    return parseDate(a.dateOfBirth) -
      parseDate(b.dateOfBirth);
  })
);

function parseDate(str) {
  var tokens = str.split(/\D/);
  while (tokens.length < 5)
    tokens.push(0);

  return new Date(tokens[2], tokens[1]-1, tokens[0], tokens[3]||0, tokens[4]||0);
}

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370989

Since you just have the year/month/day, it's pretty trivial to split up the dateOfBirth string, convert to a single number, and sort by that number, without any need to mess with Dates:

var obj = [{
  "id": 1,
  "dateOfBirth": "1.7.1990"
}, {
  id: 2,
  dateOfBirth: "28.10.1950"
}, {
  "id": 4,
  "dateOfBirth": "4.02.1976"
}];

function valueFromDOBString(str) {
  const values = str.split('.').map(Number);
  return values[0] + values[1] * 100 + values[2] * 10000;
}
const sortedObj = obj.sort((a, b) => {
  return valueFromDOBString(b.dateOfBirth) - valueFromDOBString(a.dateOfBirth);
});
console.log(sortedObj);

Upvotes: 1

Related Questions