Donate

How To Sort Dates With Invalid Values In JavaScript

Given the sorting function below to sort dates, this doesn't add checking for invalid date values. In return, the sorting doesn't do any effect on the data provided.
var DateSortWithValidation = function (a, b) {
 var dateA = new Date(a);
 var dateB = new Date(b);
 if (dateA < dateB)
  return -1;
 if (dateA > dateB)
  return 1;

 return 0;
};
So I made a little modification to the function using isNan() for date validation which sorts the dates properly.
var DateSortWithValidation = function (a, b) {

 var dateA = new Date(a);
 var dateB = new Date(b);

 if (isNaN(dateA)) {
  return 1;
 }
 else if (isNaN(dateB)) {
  return -1
 }
 else {
  if (dateA < dateB)
   return -1;
  else if (dateA > dateB)
   return 1;
  else
   return 0;
 }         
};
Usage of the function.
$(document).ready(function () {
 var dates = [
  new Date('08/25/2018'),
  new Date('test'),
  new Date('09/15/2018'),
  new Date('-'),
  new Date('02/03/2018'),
  new Date('04/25/2018'),
  new Date('06/18/2018'),
 ];

 dates.sort(DateSortWithValidation);
});

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.