agyanadda@gmail.com

JS Dates

Modern JS and Best Practices 1 min read Updated Dec 1, 2026 Topic 34 of 38

The Date object works with dates and times.

const now = new Date();
const exam = new Date('2026-03-15');

Get parts

Method Returns
getFullYear() 2026
getMonth() 0–11 (January is 0)
getDate() day of month 1–31
getDay() weekday 0–6 (Sunday is 0)
getHours(), getMinutes() time

Format for users

now.toLocaleDateString('en-IN', { day: 'numeric', month: 'long', year: 'numeric' });
// '1 December 2026'

Difference between dates

Subtracting dates gives milliseconds: (exam - now) / (1000 * 60 * 60 * 24) gives days.

Example

Example — Live clock and days left HTML
<h2 id="clock"></h2>
<p id="today"></p>
<p id="left"></p>

<script>
  function tick() {
    const now = new Date();
    document.getElementById('clock').textContent = now.toLocaleTimeString('en-IN');
    document.getElementById('today').textContent =
      now.toLocaleDateString('en-IN', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });

    const newYear = new Date(now.getFullYear() + 1, 0, 1);
    const days = Math.ceil((newYear - now) / (1000 * 60 * 60 * 24));
    document.getElementById('left').textContent = days + ' days to New Year';
  }
  tick();
  setInterval(tick, 1000);
</script>

Test Yourself With Exercises

Exercise 1 Multiple Choice

What does getMonth() return for January?

Exercise 2 True / False

Subtracting two dates gives the difference in milliseconds.

Exercise 3 Fill in the Blank

new ___() creates the current date and time.

Frequently Asked Questions

Time zones. new Date('2026-03-15') is read as UTC midnight, which can be the previous day in some zones. Use new Date(2026, 2, 15) for local dates.