Date.parse()

ES1+

Parses a string representation of a date and returns the number of milliseconds since UNIX epoch.

Syntax

Date.parse(dateString)

Parameters

dateString string

A string representing a date

Return Value

number

The number of milliseconds since UNIX epoch, or NaN if invalid

Examples

JavaScript
console.log(Date.parse('2024-01-15'));
console.log(Date.parse('January 15, 2024'));
console.log(Date.parse('invalid'));
Output:
// 1705276800000 1705276800000 NaN

📌 When to Use

Use Date.parse() when converting date strings from APIs or user input to timestamps for calculations and comparisons.

⚠️ Common Mistakes

Assuming consistent parsing across browsers - Date.parse() behavior varies between browsers for non-ISO formats.

Not checking for NaN when parsing potentially invalid date strings.

Using locale-dependent formats like "MM/DD/YYYY" which may be interpreted differently.

✅ Best Practices

Always use ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ) for reliable cross-browser parsing.

Validate the result: if (isNaN(Date.parse(dateString))) handle the error.

⚡ Performance Notes

Date.parse() is fast for ISO format strings. For complex date parsing needs, consider libraries like date-fns or Luxon which offer more reliable parsing.

🌍 Real World Example

Date Input Validator

Validate and normalize user-provided date strings with proper error handling.

function validateAndParseDate(dateString) {
  const timestamp = Date.parse(dateString);

  if (isNaN(timestamp)) {
    return {
      valid: false,
      error: 'Invalid date format. Please use YYYY-MM-DD.'
    };
  }

  const date = new Date(timestamp);
  const now = new Date();

  return {
    valid: true,
    timestamp,
    isoString: date.toISOString(),
    isPast: date < now,
    isFuture: date > now
  };
}

console.log(validateAndParseDate('2024-06-15'));
// { valid: true, timestamp: 1718409600000, isoString: '2024-06-15T00:00:00.000Z', isPast: false, isFuture: true }

console.log(validateAndParseDate('not a date'));
// { valid: false, error: 'Invalid date format. Please use YYYY-MM-DD.' }

Related Methods