1

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')}

2 Answers 2

1

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)

}

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.