6 examples of 'js invalid date' in JavaScript

Every line of 'js invalid date' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your JavaScript code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
15export function getValidDate(date: unknown): Date {
16 if (typeof date === 'undefined') {
17 throw new Error('expects a date');
18 }
19
20 date = date || new Date();
21 if (date instanceof Date) {
22 return date;
23 }
24
25 if (typeof date === 'number') {
26 if (isValidDate(date)) date = new Date(date);
27 }
28
29 if (typeof date === 'string') {
30 if (!isValidDate(date)) {
31 date = date.replace(/-/g, '/');
32 }
33
34 if (isValidDate(date as string)) {
35 date = new Date(date as string);
36 }
37 }
38
39 return date as Date;
40}
1function isValidDate(value: number | string) {
2 return !Number.isNaN(+new Date(value));
3}
87function isDateValid(value) {
88 const matched = value.match(dateRe);
89
90 if (matched) {
91 const epoch = Date.parse(value);
92 if (!epoch && epoch !== 0) return false;
93
94 const d = new Date(epoch);
95 d.setTime(d.getTime() + d.getTimezoneOffset() * 60 * 1000);
96
97 if (
98 d.getFullYear() == matched[1] &&
99 d.getMonth() + 1 == +matched[2] &&
100 d.getDate() == +matched[3]
101 ) {
102 return true;
103 }
104 }
105
106 return false;
107}
3function isValid(date){
4 if(date.length !== 6) return false;
5
6 var month = parseInt(date[4] + date[5]);
7 if(month > 12 || month === 0) return false;
8
9 var today = getToday();
10 if(parseInt(today) - parseInt(date) < 0) return false;
11
12 return !isNaN(parseInt(date));
13}
1export function isValidDate(year: number, month: number, date?: number): boolean {
2 const d = new Date(year, month, date);
3
4 const dateValid = d.getDate() == date;
5 const monthValid = d.getMonth() == month;
6 const yearValid = d.getFullYear() == year;
7 const valid = dateValid && monthValid && yearValid;
8
9 return valid;
10}
4export function parseDateString(date, separator = '-') {
5 // Expects format MM-yyyy by default: no dates
6 let datePieces = date.split(separator);
7 if (datePieces.length === 2) {
8 if (datePieces[0] < 1 || datePieces[0] > 12) {
9 throw new Error('Not a valid month value');
10 }
11 let firstOfMonth = new Date(datePieces[1], datePieces[0] - 1, 1);
12 if (isValid(firstOfMonth)) {
13 return firstOfMonth;
14 }
15 }
16 // what to return if not valid?
17 throw new Error(`Please use format MM${separator}yyyy`);
18}

Related snippets