Skip to main content
JavaScript Basics
CHAPTER 14 Beginner

JavaScript Dates and Time

Updated: May 12, 2026
20 min read

# JavaScript Dates and Time

Every application deals with time. When was this post published? Has the user's session expired? What is today's date?

In this chapter, we will learn how to capture, format, and manipulate dates and times using JavaScript's built-in Date object.

1. Introduction

Unlike Strings or Numbers, JavaScript does not have a "Date" primitive data type. Instead, you must create a new instance of the Date object to work with dates and times.

By default, JavaScript will use the browser's time zone and display the date as a full text string. It stores dates under the hood as the number of milliseconds that have passed since January 1, 1970 (known as the Unix Epoch).

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Create a Date object representing the current time.
  • Create a Date object for a specific past or future date.
  • Use "Get" methods to extract the year, month, day, hours, and minutes.
  • Understand the zero-index trap of JavaScript months.
  • Format dates into readable strings.
  • Build a working real-time Digital Clock mini-project.

3. Creating a Date Object

You create a date object using the new Date() constructor. There are 4 ways to initialize a new date:

  1. 1. new Date() (Current date and time)
  1. 2. new Date(year, month, day, hours, minutes, seconds, milliseconds) (Specific date)
  1. 3. new Date(milliseconds) (Milliseconds since Jan 1, 1970)
  1. 4. new Date(date string) (Create from a string)

javascript
1234
// Example
const rightNow = new Date();
console.log(rightNow); 
// Output: Wed Oct 18 2023 14:22:31 GMT-0400 (Eastern Daylight Time)

4. The JavaScript Month Trap

CRITICAL RULE: In JavaScript, Months are zero-indexed (just like arrays).

  • January is 0.
  • February is 1.
  • December is 11.

Days of the month (getDate()) are normal (1-31), but Days of the week (getDay()) are also zero-indexed (Sunday = 0, Monday = 1, Saturday = 6).

---

5. Real-world Examples & Code Snippets

Example 1: Creating Specific Dates

javascript
1234
// Example JavaScript
// Format: Year, Month (0-11), Day, Hour, Minute, Second
const myBirthday = new Date(1995, 10, 15); // November 15, 1995!
console.log(myBirthday);

Example 2: Creating Dates from Strings

If you omit the specific arguments and just pass a string, JavaScript will try its best to parse it. It is usually best to use the ISO standard format: YYYY-MM-DD.

javascript
123
// Example JavaScript
const date1 = new Date("2024-12-25"); // Christmas 2024
const date2 = new Date("October 13, 2024 11:13:00");

Example 3: "Get" Methods (Extracting Data)

Once you have a Date object, you can pull specific pieces of information out of it.

javascript
123456789
// Example JavaScript
const d = new Date(); // Let's pretend it's July 4th, 2024, 2:30 PM

console.log(d.getFullYear()); // 2024
console.log(d.getMonth());    // 6 (July is index 6!)
console.log(d.getDate());     // 4 (The 4th of the month)
console.log(d.getDay());      // 4 (Thursday)
console.log(d.getHours());    // 14 (2 PM in 24hr format)
console.log(d.getMinutes());  // 30

Example 4: Getting the Timestamp (Milliseconds)

The getTime() method returns the number of milliseconds since Jan 1, 1970. This is incredibly useful for measuring how long a task took to execute, or comparing which of two dates is older.

javascript
123
// Example JavaScript
const d = new Date();
console.log(d.getTime()); // Output: 1697654345211

Example 5: "Set" Methods (Modifying Data)

You can change a Date object after you create it using Set methods.

javascript
123456
// Example JavaScript
const d = new Date(); // Right now
d.setFullYear(2030);  // Change year to 2030
d.setMonth(0);        // Change month to January

console.log(d); // Output: Jan ... 2030...

Example 6: Formatting Dates nicely

The default output of new Date() is ugly for users. You can format it beautifully.

javascript
1234567891011
// Example JavaScript
const d = new Date();

// To standard date string (e.g., "10/18/2023")
console.log(d.toLocaleDateString()); 

// To standard time string (e.g., "2:30:15 PM")
console.log(d.toLocaleTimeString()); 

// To full readable string
console.log(d.toLocaleString()); 

Example 7: Creating an Array of Month Names

Because getMonth() returns a number (0-11), developers often use an array to get the text name of the month.

javascript
1234567
// Example JavaScript
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

const d = new Date();
let currentMonthName = months[d.getMonth()];

console.log("We are currently in " + currentMonthName);

Example 8: Comparing Dates

Because dates are stored as milliseconds under the hood, you can use standard comparison operators (> , <) to compare them.

javascript
12345678910
// Example JavaScript
let today = new Date();
let eventDate = new Date();
eventDate.setFullYear(2025); // Push event to next year

if (eventDate > today) {
    console.log("The event is in the future.");
} else {
    console.log("The event has already passed.");
}

Example 9: Calculating Time Difference

To find out how many days exist between two dates, you subtract them to get the difference in milliseconds, then do some math.

javascript
123456789101112
// Example JavaScript
let date1 = new Date("2024-01-01");
let date2 = new Date("2024-01-10");

// Difference in milliseconds
let diffInMs = date2 - date1;

// Convert ms -> seconds -> minutes -> hours -> days
let msInOneDay = 1000 * 60 * 60 * 24; 
let daysDifference = diffInMs / msInOneDay;

console.log("Difference in days: " + daysDifference); // Output: 9

Example 10: Padding Single Digits

When making clocks, getMinutes() might return 5. A clock showing 10:5 looks broken; it should be 10:05.

javascript
123456
// Example JavaScript
let m = 5;
// Using ternary operator to add a zero if less than 10
let formattedMinute = m < 10 ? "0" + m : m;

console.log(formattedMinute); // Output: "05"

---

6. Common Mistakes for Beginners

  1. 1. The Month Trap: Writing new Date(2024, 1, 1) and expecting January 1st. It will actually be February 1st because index 1 is February!
  1. 2. Confusing getDay() with getDate(): getDate() gives you the day of the month (1-31). getDay() gives you the day of the week (0-6).
  1. 3. Assuming timezone consistency: If you fetch a date string from a server in London and open it in a browser in New York, new Date() will automatically convert it to New York time. This is a common source of bugs in enterprise apps.

7. Best Practices

  • Always use toLocaleDateString() and toLocaleTimeString() to format dates for users, as it automatically respects the user's computer locale settings (e.g., MM/DD vs DD/MM).
  • For very complex date manipulation (timezones, recurring calendar events), professional developers rarely use the native Date object. They use libraries like date-fns or Moment.js.

8. Mini Project: Real-time Digital Clock

Let's build a clock that updates every second on the screen. (We will use a timer function we officially cover in Chapter 27, but it's simple enough to use here!)

HTML:

html
12345678910111213141516171819
<!-- Example HTML -->
<!DOCTYPE html>
<html>
<head>
    <style>
        /* Example CSS */
        body { font-family: Arial; padding: 50px; background: #222; color: #fff; text-align: center; }
        .clock { font-size: 60px; font-weight: bold; letter-spacing: 5px; text-shadow: 0 0 20px rgba(0, 255, 255, 0.5); color: cyan; }
        .date { font-size: 20px; color: #aaa; margin-top: 10px; }
    </style>
</head>
<body>

    <div class="clock" id="timeDisplay">00:00:00</div>
    <div class="date" id="dateDisplay">Loading...</div>

    <script src="clock.js"></script>
</body>
</html>

clock.js:

javascript
123456789101112131415161718192021222324252627282930313233
// Example JavaScript
function updateClock() {
    const now = new Date();
    
    let hours = now.getHours();
    let minutes = now.getMinutes();
    let seconds = now.getSeconds();
    
    // Determine AM or PM
    let ampm = hours >= 12 ? &#039;PM&#039; : &#039;AM&#039;;
    
    // Convert to 12-hour format
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    
    // Pad single digits with zeros
    hours = hours < 10 ? "0" + hours : hours;
    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;
    
    // Build time string
    let timeString = hours + ":" + minutes + ":" + seconds + " " + ampm;
    
    // Update DOM
    document.getElementById("timeDisplay").innerHTML = timeString;
    document.getElementById("dateDisplay").innerHTML = now.toDateString();
}

// Call it once immediately to prevent 1-second delay
updateClock();

// Built-in JS function: Run updateClock every 1000 milliseconds (1 second)
setInterval(updateClock, 1000);

9. Exercises

  1. 1. Create a variable now holding a new Date object.
  1. 2. Console log the current full year using a method from the now object.
  1. 3. Console log the current month. Remember the output is a zero-indexed number!

10. MCQs (Multiple Choice Questions)

Q1: What will new Date(2024, 0, 1) create? A) February 1, 2024 B) January 1, 2024 C) Error D) December 1, 2024 *Answer: B (Because Month 0 is January)*

Q2: Which method returns the day of the week (0-6)? A) getDate() B) getDay() C) getDayOfWeek() D) getTime() *Answer: B*

Q3: How are dates fundamentally tracked behind the scenes in JavaScript? A) As a String in ISO format B) As an Object with 6 properties C) As Milliseconds since Jan 1, 1970 D) As a 64-bit Hash *Answer: C*

11. Interview Questions

Q: Why do developers often convert Dates to Milliseconds (getTime()) before comparing them? *A: Comparing Date objects directly using == or === will return false even if they represent the exact same millisecond in time, because they are comparing Object references in memory, not the values. Converting them to primitive numbers (milliseconds) allows for strict, accurate mathematical comparison.*

12. FAQs

Q: Can I get the user's timezone? *A: Yes! You can use Intl.DateTimeFormat().resolvedOptions().timeZone to get a string like "America/New_York".*

13. Summary

  • Create a date with new Date().
  • Months and Days of the Week are zero-indexed!
  • Use getFullYear(), getMonth(), getDate(), getHours(), getMinutes() to extract data.
  • Use setFullYear(), setMonth(), etc., to modify data.
  • getTime() returns milliseconds since Jan 1, 1970.
  • toLocaleDateString() formats dates perfectly for UI display.

14. Next Chapter Recommendation

We've spent a lot of time writing logical code and running it in the console. It's time to fully master the bridge between JavaScript and the visual website. In the next chapter, JavaScript DOM Basics, we will deeply explore the Document Object Model and how JS interacts with HTML.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·