It's not clear what you are asking.
> function CompareDates(id) {
What is id? Is it a string or a time value? Function names starting with a capital letter are, by convention, reserved for constructors, so better to use:
function compareDates() {
Also, this doesn't seem to compare dates, is the name still appropriate? Or maybe it's a work in progress. :-)
> var months = new Array(12);
> months[1]= "Jan";
...
> months[12] = "Dec";
Consider using an array literal. It seems you are trying to convert a Date object month number to the English month abbreviation. In that case, make the array zero indexed (as others have suggested):
var months = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'];
> var d = new Date(id);
Hopefully id is a time value since letting the Date constructor parse strings is problematic and inconsistent in browsers. I'll assume that it's creating a suitable Date object.
> var retVal =d.getDate() + ' ' + months[d.getDate()] + ' ' + d.getFullYear()
To get the appropriate month name:
var retVal = d.getDate() + ' ' + months[d.getMonth()] + ' ' + d.getFullYear();
however it's not common to use a space as a separator, "-" and "/" are more common.
As has also been said, once id is converted to a Date, it will always fit the parameters for a valid date. If it can't be converted to a valid date, it will evaluate to NaN
.
However, if id is a string (and it should not be, see above) like "23/5/2014" then you can vlidate it using the answers to How to validate a date.
Edit
So it seems id is a string. You can't specify a format for Date.parse, it may accept particular strings but it's generally unreliable so manually parse the string. Assuming it's in d/m/y format:
// Expects d/m/y
function parseDMY(s) {
var b = s.split(/\D/);
return new Date(b[2], --b[1], b[0]);
}
The date can be validated using:
// Expects d/m/y
function isValidDate(s) {
var b = s.split(/\D/);
var d = parseDMY(s);
return !!d && d.getFullYear() == b[2] && d.getDate() == b[0];
}
console.log(isValidDate('29/2/2014')); // false
console.log(isValidDate('29/2/2016')); // true
The above will return either true or false depending on whether it is passed a valid date in d/m/y format. For some browsers, the above will fail if the year is from 1 to 99 as they assume such dates are 20th century and make them 1901 to 1999.
If you wish to also handle dates in the first century, use:
// Expects d/m/y
function parseDMY(s) {
var b = s.split(/\D/);
var d = new Date();
d.setHours(0,0,0,0);
d.setFullYear(b[2], --b[1], b[0]);
return d;
}