Skip to content

Instantly share code, notes, and snippets.

@wcarss
Last active August 26, 2019 21:45
Show Gist options
  • Save wcarss/4646b661dee13eda1ec91ecb4a4e4506 to your computer and use it in GitHub Desktop.
Save wcarss/4646b661dee13eda1ec91ecb4a4e4506 to your computer and use it in GitHub Desktop.
javascript to check if a string is a valid YYYY-MM-DD-style date or datetime. This is more permissive than ISO 8601 but less permissive than the Date() constructor.
/*
* returns true/false on "is this string a valid date/datetime string"
*
* any credit for coolness goes to https://stackoverflow.com/a/44198641,
* and any blame for wrongness goes to me. :)
*
*/
const isValidDate = dateString => {
let date = new Date(dateString); // we're gonna use both :0
return (
date && // make sure it's non-falsey,
/[0-9]{4}-[0-9]{2}-[0-9]{2}/.test(dateString) && // roughly YYYY-MM-DD.* to stop e.g. new Date('0'),
Object.prototype.toString.call(date) === '[object Date]' && // is actually a date object,
!isNaN(date) // and is actually a *valid* date object.
);
};
@wcarss
Copy link
Author

wcarss commented Aug 26, 2019

e.g.

isValidDate(Date(0))
// -> false
isValidDate(null);
// -> false
isValidDate("hello");
// -> false
isValidDate("2012");
// -> false
isValidDate("2");
// -> false
isValidDate("2012-01");
// -> false
isValidDate("2012-01-1");
// -> false
isValidDate("2012-01-01");
// -> true
isValidDate("2012-01-01T00:00");
// -> true
isValidDate("2012-01-01 00:00");
// -> true
isValidDate("2012-01-01T00:00:00.0");
// -> true
isValidDate("2012-01-01 00:00:00.0");
// -> true
isValidDate("2012-01-01 00:00:00.1");
// -> true
isValidDate("2012-01-01T00:00:0");
// -> false
isValidDate("2012-01-01 ok:00:00");
// -> false
isValidDate("2012-01-01 00:00:00Z");
// -> true
isValidDate("2012-01-01 00:00:00 GMT");
// -> true
isValidDate("2012-01-01 GMT");
// -> true
isValidDate("2012-01-01 +0500");
// -> false
isValidDate(new Date('2012-01-01 00:00:00').toGMTString()) // doesn't work with non-YYYY-MM-DD strings
// -> false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment