user4408375
user4408375

Reputation:

How to sort a string which has date values using jquery

I need to check if a string is a date or not. If the string is a date then I need to sort it by ascending order.

I am getting values like

d["dates"] has values ["1/10/1978 0:00", "2/3/1988 0",.....,"1/10/1978 23:00"].

First I need to check whether it is date or not if its date I need to sort ascending order.

Any help is good.

I have tried this

var date = Date.parse(d["dates"]);
if(isNaN(date)){ console.log('not date')}

Upvotes: 1

Views: 1321

Answers (2)

user4408375
user4408375

Reputation:

To ensure string is date:

 var sortedKey1 = new Array();
 var date = Date.parse(d["dates"]);
 sortedKey1 = d["dates"]
 if(isDate(date)){
     console.log('inside if of isDate(date)')
    KEY_IS_DATE = true;
 }
 function isDate(date) {
       return (new Date(date) !== "Invalid Date" && !isNaN(new Date(date)));

 }

For sorting according to date:

if(KEY_IS_DATE){
var sortedKey = sortedKey1.sort(function(a,b) { 
    return new Date(a).getTime() - new Date(b).getTime() 
});
console.log(sortedKey)

}

Upvotes: 1

sajanyamaha
sajanyamaha

Reputation: 3198

Iterate all array elements and do a date parse saving successful parse to another array.

Working sample here

and sort can be done using various JS/Jquery Plugins.

var stringArry = ["1/10/1978 0:00", "2/3/1988 0", "1/10/1978 23:00"];
var dateArray = [];

$.each(stringArry, function (index, value) {
    var timestamp = Date.parse(value)
    if (isNaN(timestamp) == false) {
        var newDate = new Date(timestamp);
        dateArray.push(newDate);
    }
});

$.each(dateArray, function (index, value) {
    alert(index + ": " + value);
});

Upvotes: 0

Related Questions