Last active
December 1, 2019 22:03
-
-
Save Tnifey/e97427f15d35d206c758e041c7bf3718 to your computer and use it in GitHub Desktop.
function checks if date exists/ is date valid
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function dateExists(year: number, month: number, day: number): boolean { | |
if (typeof year !== "number") year = Number.parseInt(`${year}`, 10); | |
if (typeof month !== "number") month = Number.parseInt(`${month}`, 10); | |
if (typeof day !== "number") day = Number.parseInt(`${day}`, 10); | |
if (year && month && day) { | |
if (day >= 1 && day <= 31 && month >= 1 && month <= 12) { | |
const d = `${day}`.padStart(2, "0"); | |
const m = `${month}`.padStart(2, "0"); | |
const y = `${year}`.padStart(4, "0"); | |
const datestring = `${y}-${m}-${d}`; // 2019-02-28 | |
const date = new Date(datestring).toJSON(); // 2019-02-28T00:00:00.000Z | |
return date.startsWith(datestring); | |
} | |
} | |
return false; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import dateExists from "./dateExists.ts"; | |
console.log(dateExists(2019, 2, 29)); // false | |
// 2019 is not a leap year, then February 29, 2019 is not valid |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment