Created
July 28, 2011 16:32
-
-
Save cowboy/1111886 to your computer and use it in GitHub Desktop.
JavaScript: Return date, if valid.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function dateIfValid(y, m, d) { | |
var date = new Date(y, --m, d); | |
return !isNaN(+date) && date.getFullYear() == y && date.getMonth() == m && date.getDate() == d && date; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function dateIfValid(y,m,d){var _=new Date(y,--m,d);return!isNaN(+_)&&_.getFullYear()==y&&_.getMonth()==m&&_.getDate()==d&&_} |
date.getTime()
could be +date
if you wanted to. Also, @Kambfhase pointed out you could use --m
to crunch some more bytes.
function isDateValid(y, m, d) {
var date = new Date(y, --m, d);
return !isNaN(+date) && date.getFullYear() == y && date.getMonth() == m && date.getDate() == d;
}
Since I needed the created date object, I wrote it like this:
function get_valid_date(year, month, day){
var y = parseInt( year, 10 );
var m = parseInt( month, 10 );
var d = parseInt( day, 10 );
var date = new Date( y, m - 1, d );
if ( !isNaN(date.getTime()) && date.getFullYear() == y &&
date.getMonth() == m - 1 && date.getDate() == d ) {
return date;
} else {
return;
}
}
Ok, so I changed it to dateIfValid
which now returns a date object, if the date is valid. Even more useful, and still tweetable!
I know the regexp could be mucked with, but you could do smth like below to reduce the day
+ year
check.
function dateIfValid(y, m, d) {
var date = new Date(y, --m, d);
return (/(\d+) .*?(\d{4})/.exec(date)||'').slice(1) == d+','+y && date.getMonth() == m && date;
}
golf'ed to
function dateIfValid(y,m,d,_){
return(/(\d+) .*?(\d{4})/.exec(_=new Date(y,--m,d))||'').slice(1)==d+','+y&&_.getMonth()==m&&_
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In a tweet as well.