Skip to content

Instantly share code, notes, and snippets.

@marklundin
Created December 12, 2012 10:23
Show Gist options
  • Save marklundin/4266684 to your computer and use it in GitHub Desktop.
Save marklundin/4266684 to your computer and use it in GitHub Desktop.
Returns the earliest possible date from all possible combinations of DD/MM/YY if one is possible
var t ='31/9/73'.split('/');
for( var i = 0, d, o = t.slice(0), result = Number.MAX_VALUE; i < 6 ; i++, t.splice( 2, 0, t.shift() ))
{
d = new Date( [ t[0], t[1], t[2] < 2000 ? +t[2]+2000+"": t[2] ].join('/') );
result = (d.getFullYear() == (t[2] < 2000 ? +t[2]+2000: t[2]) &&
d.getDate() == t[1] &&
d.getMonth() + 1 == t[0]) ? new Date( Math.min( d.valueOf() || result, result )) : result;
if( i == 2 ) t[1] = t.splice( 0, 1, t[1])[0];
}
console.log(( isNaN( result ) || result == Number.MAX_VALUE ) ? o.join('/') + " is illegal" : result.getFullYear() + '-' + ( "00" + ( result.getMonth() + 1 )).slice(-2) + '-' + ( "00"+result.getDate() ).slice(-2) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment