Skip to content

Instantly share code, notes, and snippets.

@alfasin
Created December 4, 2017 06:04
Show Gist options
  • Save alfasin/49d7bec5ade26cd1caef812268deac2f to your computer and use it in GitHub Desktop.
Save alfasin/49d7bec5ade26cd1caef812268deac2f to your computer and use it in GitHub Desktop.
Stolen from: http://jsfiddle.net/niklasvh/xfrLm/ a neat way to verify that a given date (in string format) is valid
/*
* Takes input as date-dtring in the format of mm/dd/yyyy and verifies that it's a valid date
* by creating a date object out of it and comparing the year/month/day to the given ones
*/
function isDate(date) {
var objDate, // date object initialized from the date string
mSeconds, // date in milliseconds
day, // day
month, // month
year; // year
// date length should be 10 characters (no more no less)
if (date.length !== 10) {
return false;
}
// third and sixth character should be '/'
if (date.substring(2, 3) !== '/' || date.substring(5, 6) !== '/') {
return false;
}
// extract month, day and year from the date (expected format is mm/dd/yyyy)
// subtraction will cast variables to integer implicitly (needed
// for !== comparing)
month = date.substring(0, 2) - 1; // because months in JS start from 0
day = date.substring(3, 5) - 0;
year = date.substring(6, 10) - 0;
// test year range
if (year < 1000 || year > 3000) {
return false;
}
// convert date to milliseconds
mSeconds = (new Date(year, month, day)).getTime();
// initialize Date() object from calculated milliseconds
objDate = new Date();
objDate.setTime(mSeconds);
// compare input date and parts from Date() object
// if difference exists then date isn't valid
if (objDate.getFullYear() !== year ||
objDate.getMonth() !== month ||
objDate.getDate() !== day) {
return false;
}
// otherwise return true
return true;
}
console.log(isDate('1/1/2017')) // false - not in format mm/dd/yyyy
console.log(isDate('01/01/2017')) // true
console.log(isDate('13/01/2017')) // false - invalid date
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment