0
0
JavascriptHow-ToBeginner · 3 min read

How to Parse Date String in JavaScript: Simple Guide

In JavaScript, you can parse a date string by passing it to the Date constructor or using Date.parse(). Both convert the string into a timestamp or a Date object you can work with.
📐

Syntax

To parse a date string, use the Date constructor or Date.parse() method:

  • new Date(dateString): Creates a Date object from the string.
  • Date.parse(dateString): Returns the timestamp (milliseconds since Jan 1, 1970) or NaN if invalid.

The dateString should be in a recognized format like ISO 8601 (YYYY-MM-DDTHH:mm:ss).

javascript
const date1 = new Date('2024-06-01T12:30:00');
const timestamp = Date.parse('2024-06-01T12:30:00');
💻

Example

This example shows how to parse a date string into a Date object and get its components like year, month, and day.

javascript
const dateString = '2024-06-01T12:30:00';
const dateObj = new Date(dateString);

console.log('Date object:', dateObj);
console.log('Year:', dateObj.getFullYear());
console.log('Month:', dateObj.getMonth() + 1); // Months start at 0
console.log('Day:', dateObj.getDate());
Output
Date object: Sat Jun 01 2024 12:30:00 GMT+0000 (Coordinated Universal Time) Year: 2024 Month: 6 Day: 1
⚠️

Common Pitfalls

Common mistakes when parsing date strings include:

  • Using unsupported or ambiguous date formats that JavaScript can't parse reliably.
  • Forgetting that months start at 0 in JavaScript Date objects.
  • Relying on Date.parse() without checking for NaN on invalid strings.

Always use ISO 8601 format for best compatibility.

javascript
const wrongDate = new Date('06/01/2024'); // May be interpreted differently in browsers
console.log('Wrong date:', wrongDate);

const rightDate = new Date('2024-06-01T00:00:00');
console.log('Right date:', rightDate);
Output
Wrong date: Sat Jun 01 2024 00:00:00 GMT+0000 (Coordinated Universal Time) Right date: Sat Jun 01 2024 00:00:00 GMT+0000 (Coordinated Universal Time)
📊

Quick Reference

MethodDescriptionReturns
new Date(dateString)Creates a Date object from a date stringDate object or Invalid Date
Date.parse(dateString)Parses a date string and returns timestampNumber (milliseconds) or NaN
Date.getFullYear()Gets the year from a Date objectYear as number
Date.getMonth()Gets the month (0-11) from a Date objectMonth as number (0 = January)
Date.getDate()Gets the day of the month from a Date objectDay as number (1-31)

Key Takeaways

Use the Date constructor with ISO 8601 strings for reliable parsing.
Date.parse() returns a timestamp or NaN if the string is invalid.
Months in JavaScript Date objects start at 0, so add 1 when displaying.
Avoid ambiguous date formats like MM/DD/YYYY to prevent errors.
Always check for invalid dates when parsing user input.