JS Foundations #13 — Date & Time

Date constructor (beware month is 0-based), getTime, Date.now, formatting with toISOString/toLocaleDateString, date arithmetic, and performance.now for high-res timing.

7 min read
JavaScript
Fundamentals
Date

TABLE OF CONTENTS

JavaScript's Date object handles timestamps, formatting, and time arithmetic. It's used in interviews for timing (throttle, debounce), timestamp generation, and date manipulation. This covers the practical methods you'll reach for.


1. Creating Dates

Loading editor...

Month is 0-based0 = January, 11 = December. This is the most common Date pitfall.


2. Getting Timestamps

Loading editor...

Interview use: Date.now() in throttle (#9) to check if enough time has elapsed since the last call.


3. Getting Date Components

Loading editor...

Always prefer UTC methods to avoid timezone surprises. Store and transmit dates in ISO 8601 / UTC.


4. Setting Date Components

Loading editor...

Setters mutate the Date object. They auto-correct overflow: setDate(0) goes to the last day of the previous month.


5. Date Arithmetic

Subtract dates to get milliseconds; divide to get other units:

Loading editor...


6. Formatting Dates

ISO 8601 (Preferred for Storage/Transmission)

Loading editor...

Locale-Aware Formatting

Loading editor...

Human-Readable

Loading editor...


7. performance.now() — High-Resolution Timing

For measuring code execution time, use performance.now() instead of Date.now():

Loading editor...

performance.now() returns milliseconds with microsecond precision (fractional) and is monotonic — it never goes backwards, unlike system clock changes.

Interview use: Measuring algorithm runtime in complexity analysis.


8. Parsing Dates Reliably

Loading editor...


9. Checking Validity

Loading editor...


Quick Reference

MethodReturns
Date.now()Current timestamp (ms)
new Date()Current date/time
new Date(ms)Date from timestamp
new Date(str)Date from ISO string
d.getTime()Timestamp (ms)
d.getFullYear()Year (4 digits)
d.getMonth()Month (0–11)
d.getDate()Day of month (1–31)
d.getHours() / getMinutes() / getSeconds()Time components
d.setDate(n)Set day (mutates)
d.toISOString()ISO 8601 string
d.toLocaleDateString(locale)Locale-formatted date
performance.now()High-res monotonic time

Interview Tips

  • Use Date.now() for timing — no need to create a Date object for a timestamp.
  • Use performance.now() for benchmarks — higher precision and monotonic.
  • Use UTC methods for consistencygetUTCFullYear(), not getFullYear().
  • Remember month is 0-basednew Date(2024, 0) is January, not December.

Related Articles


Let's Connect

© 2026 Naveen Karthik // Built with React & MUI