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&&_}
@cowboy
Copy link
Author

cowboy commented Jul 28, 2011

In a tweet as well.

@mathiasbynens
Copy link

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

@jspath
Copy link

jspath commented Jul 28, 2011

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

@cowboy
Copy link
Author

cowboy commented Jul 28, 2011

Ok, so I changed it to dateIfValid which now returns a date object, if the date is valid. Even more useful, and still tweetable!

@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