JavaScript provides a built-in Date object to work with dates and times — including year, month, day, hour, minutes, seconds, and milliseconds.
How to Create Dates
1. Current Date and Time
2. Using a Date String
3. Using Milliseconds from 1970
4. Using Year, Month, Day, etc.
Month Index Starts from 0 ? January = 0, February = 1, ..., December = 11
Date Formats
JavaScript supports ISO 8601 date format:
Other examples of accepted formats:
Some formats may not work consistently across browsers — prefer standard formats like YYYY-MM-DD.
Convert Date Formats
Once you have a date object, you can convert it to different formats:
Custom Date Format (DD-MM-YYYY)
You can manually format the date:
Compare Dates
You can compare two dates using <, >, ==, etc.
Dates are compared by their numeric timestamp behind the scenes.
Summary Table
| Action | Example Code |
|---|---|
| Create current date | new Date() |
| From date string | new Date("Feb 3, 2015") |
| From components | new Date(2023, 0, 15, 10, 30) |
| From milliseconds | new Date(1000) |
| Format to readable | date.toDateString() |
| Format to ISO | date.toISOString() |
| Convert to local | date.toLocaleString() |
| Compare dates | if (date1 > date2) { ... } |
| Custom format | Use getDate(), getMonth(), getFullYear() |
Tips
Always use
new Date()to create a date object.Prefer ISO format (
YYYY-MM-DD) for compatibility.Remember that months are zero-based (Jan = 0).
Use libraries like Moment.js or date-fns for advanced formatting and manipulation.
