How to parse a date from a string
Short answer
The standard ISO format YYYY-MM-DDTHH:mm is understood by new Date() directly:
const date = new Date('2025-03-15T14:30');
console.log(date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours());Output:
2025 3 15 14day.month.year
Other formats are better split by hand: their parsing differs between browsers:
const [day, month, year] = '25.12.2025'.split('.').map(Number);
const date = new Date(year, month - 1, day);
console.log(date.toDateString());Output:
Thu Dec 25 2025Checking the result
An unreadable string gives an invalid date. Its getTime() returns NaN:
const date = new Date('not a date');
console.log(Number.isNaN(date.getTime()));
console.log(String(date));Output:
true
Invalid DateCommon mistake
A date-only string like 2025-03-15 is read as midnight in UTC, not local time. West of Greenwich it becomes the previous day. Add the time or build the date from numbers:
const utc = new Date('2025-03-15');
const local = new Date('2025-03-15T00:00');
console.log(utc.toISOString());
console.log(local.getDate());Output:
2025-03-15T00:00:00.000Z
15Functions used in this recipe
- Date.parse — Parses a date string and returns a timestamp.
- Date.prototype.toISOString — Returns the date in ISO 8601 format in UTC.