Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created July 28, 2011 16:32
Show Gist options
  • Save cowboy/1111886 to your computer and use it in GitHub Desktop.
Save cowboy/1111886 to your computer and use it in GitHub Desktop.
JavaScript: Return date, if valid.
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;
}
function dateIfValid(y,m,d){var _=new Date(y,--m,d);return!isNaN(+_)&&_.getFullYear()==y&&_.getMonth()==m&&_.getDate()==d&&_}
@jdalton
Copy link

jdalton commented Jul 28, 2011

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