JavaScript Date and Time
Create, format, and modify dates in JavaScript with timestamps, UTC, and common calculations.
TL;DR
- 01Create dates using
new Datewith several input options. - 02Read date parts with
getFullYear(), change them withsetFullYear(). - 03Format dates with
toISOString()for machines andtoLocaleDateString()for humans.
Tips
- 01For complex date math like time zones, recurring events, or relative time, use a library like
date-fnsorLuxon. - 02Store dates as ISO strings or timestamps in APIs and databases, converting to a
Dateobject only for display.
Warnings
- 01JavaScript months are zero-indexed, so passing
0means January and passing11means December, not month 12. - 02Date string parsing varies by browser for non-ISO formats, so prefer ISO 8601 or
new Date(year, month, day)instead.
Creating Dates
new Date()The Date constructor accepts four different argument shapes for creating dates.
const now = new Date();From millisecondsPass a timestamp in milliseconds to create a date from a number.
const fromMs = new Date(1697040000000);From a stringPass a date string to parse a specific date in standard format.
const d = new Date("2025-10-11");From partsPass year, month (zero-indexed), day, and time parts to build a custom date.
const custom = new Date(2025, 9, 11, 15, 30);Checking validityDetects an invalid date by testing whether getTime() returns NaN.
Number.isNaN(d.getTime()); // true if invalidReading Parts
getFullYear()Reads the four-digit year directly from a Date object instance.
now.getFullYear(); // 2025getMonth()Reads the month as a zero-indexed number, where zero means January.
now.getMonth(); // 9 means OctobergetDate() and getDay()getDate() returns the day of the month; getDay() returns the weekday.
now.getDate();
now.getDay(); // 0 = SundayTime componentsUse getHours(), getMinutes(), and getSeconds() to read the time components.
now.getHours();
now.getMinutes();
now.getSeconds();getTime()Reads the date as a millisecond timestamp since the Unix epoch.
now.getTime(); // ms since epochChanging Parts
setFullYear()Every setter mutates the original Date object in place — there's no immutable version.
const date = new Date();
date.setFullYear(2026);setMonth()Changes the month in place, again starting counting from zero.
date.setMonth(0); // JanuarysetDate()Changes the day of the month, rolling over into next month.
date.setDate(1);setHours()Use extra arguments to set minutes and seconds at the same time.
date.setHours(12, 0, 0);setTime()Sets the entire date at once from a millisecond timestamp value.
date.setTime(0); // Jan 1, 1970 UTCTimestamps and UTC
Date.now()Returns the current timestamp in milliseconds since the Unix epoch.
const ts = Date.now();getUTC methodsReads times in universal coordinated time instead of the local timezone.
now.getUTCFullYear();
now.getUTCHours();Easy comparisonsTimestamps make it easy to compare or subtract two dates directly.
date1.getTime() < date2.getTime();toJSON()Runs automatically inside JSON.stringify(), which produces an ISO date string.
JSON.stringify({ d: now }); // ISO stringnew Date(ts)Convert any millisecond timestamp back into a usable Date object.
const d = new Date(1700000000000);Formatting and Math
toISOString()Formats a date for machines, always returning UTC in a sortable format.
now.toISOString();
// "2025-10-11T00:00:00.000Z"toLocaleDateString()Formats the date for the user's region for a human-readable display.
now.toLocaleDateString();Adding daysRead the current date and add to it to shift by any number of days.
const today = new Date();
today.setDate(today.getDate() + 5);Subtracting datesSubtract two dates to get the difference in milliseconds between them.
const diffMs = date1 - date2; // millisecondsConverting unitsConvert milliseconds into days or hours using simple division for clarity.
const hrs = ms / (1000 * 60 * 60);In Practice
Creates a target date, computes the whole-day difference from today, and formats both dates for display.
- 01new Date(year, month, day) builds the deadline — remember month is zero-indexed, so October is 9.
- 02Subtracting two Date objects returns the difference in milliseconds, not days.
- 03Dividing by the number of milliseconds in a day and rounding up gives a whole day count.
- 04toLocaleDateString() formats each date for display while the raw Date objects handle the math.
const today = new Date();
const deadline = new Date(2026, 9, 31); // October 31, 2026 (month is zero-indexed)
const msPerDay = 1000 * 60 * 60 * 24;
const daysLeft = Math.ceil((deadline - today) / msPerDay);
console.log(`Today: ${today.toLocaleDateString()}`);
console.log(`Deadline: ${deadline.toLocaleDateString()}`);
console.log(`${daysLeft} day(s) remaining`);FAQ
JavaScript's Date constructor takes months as zero-indexed values, so January is 0 and December is 11. Always subtract 1 when passing a human-readable month number, e.g. new Date(2024, 0, 15) for January 15th.
Use Date.now() to get milliseconds since the Unix epoch. Divide by 1000 and floor the result to get seconds: Math.floor(Date.now() / 1000). You can also call new Date().getTime() for the same millisecond result.
getMonth() returns the month in local time, based on the user's system timezone. getUTCMonth() always returns the month in UTC instead. Use UTC methods when working with server timestamps or storing dates that must be timezone-independent.
Read the current day with getDate(), add your offset, then set it back with setDate(), e.g. date.setDate(date.getDate() + 7). JavaScript automatically rolls over the month and year if the value exceeds the month's length. For anything more complex, like adding months or handling DST, use date-fns or Luxon.
Use toLocaleDateString() with a locale and options object: new Date().toLocaleDateString('en-US', { year: 'numeric', month: '2-digit', day: '2-digit' }). For a sortable ISO format use toISOString(), which always returns UTC in the format YYYY-MM-DDTHH:mm:ss.sssZ.