Manipulate Dates with JavaScript Date Object

CSSCSSBeginner
Practice Now

Introduction

In this lab, participants will explore the powerful JavaScript Date object and learn essential techniques for manipulating dates and times. Through a comprehensive, hands-on approach, students will discover how to create Date objects using various initialization methods, retrieve specific date components, format and display date information, modify dates using setter methods, and perform complex date calculations.

The lab provides practical, step-by-step guidance on working with dates in JavaScript, covering fundamental skills such as creating Date objects from current time, specific timestamps, date strings, and milliseconds since the Unix Epoch. By the end of this lab, participants will have gained a solid understanding of date manipulation techniques, enabling them to effectively handle date-related tasks in their JavaScript applications.

Create a New Date Object

In this step, you'll learn how to create new Date objects in JavaScript, which is fundamental for working with dates and times. The JavaScript Date object allows you to work with dates and times easily.

First, let's open the WebIDE and create a new JavaScript file called dates.js in the ~/project directory.

Create a new Date object with different initialization methods:

// Create a Date object representing the current date and time
let currentDate = new Date();
console.log("Current Date:", currentDate);

// Create a Date object with specific date and time
let specificDate = new Date(2023, 5, 15, 10, 30, 0);
console.log("Specific Date:", specificDate);

// Create a Date object from a date string
let stringDate = new Date("2023-06-15");
console.log("Date from String:", stringDate);

// Create a Date object using milliseconds since Unix Epoch
let millisecondDate = new Date(1686816000000);
console.log("Date from Milliseconds:", millisecondDate);

Example output:

Current Date: Thu Jun 15 2023 12:00:00 GMT+0000 (Coordinated Universal Time)
Specific Date: Thu Jun 15 2023 10:30:00 GMT+0000 (Coordinated Universal Time)
Date from String: Thu Jun 15 2023 00:00:00 GMT+0000 (Coordinated Universal Time)
Date from Milliseconds: Thu Jun 15 2023 00:00:00 GMT+0000 (Coordinated Universal Time)

Key points to remember:

  • new Date() creates a Date object with the current date and time
  • new Date(year, month, day, hours, minutes, seconds) allows creating a specific date
  • Months are zero-indexed (0-11), so June is represented by 5
  • You can create dates from strings or milliseconds since the Unix Epoch (January 1, 1970)

Retrieve Current Date Components

In this step, you'll learn how to extract specific components from a Date object. Building on the previous step, we'll use the dates.js file to demonstrate various methods for retrieving date and time components.

Open the ~/project/dates.js file and add the following code:

// Create a current date object
let currentDate = new Date();

// Retrieve individual date components
let year = currentDate.getFullYear();
let month = currentDate.getMonth(); // 0-11 (0 = January)
let day = currentDate.getDate(); // Day of the month
let hours = currentDate.getHours();
let minutes = currentDate.getMinutes();
let seconds = currentDate.getSeconds();
let milliseconds = currentDate.getMilliseconds();

// Display individual components
console.log("Year:", year);
console.log("Month:", month + 1); // Add 1 to show actual month number
console.log("Day of Month:", day);
console.log("Hours:", hours);
console.log("Minutes:", minutes);
console.log("Seconds:", seconds);
console.log("Milliseconds:", milliseconds);

// Get day of the week
let dayOfWeek = currentDate.getDay(); // 0-6 (0 = Sunday)
console.log("Day of Week:", dayOfWeek);

// Get timestamp (milliseconds since Unix Epoch)
let timestamp = currentDate.getTime();
console.log("Timestamp:", timestamp);

Example output:

Year: 2023
Month: 6
Day of Month: 15
Hours: 12
Minutes: 30
Seconds: 45
Milliseconds: 123
Day of Week: 4
Timestamp: 1686816045123

Key points to remember:

  • getFullYear() returns the four-digit year
  • getMonth() returns 0-11, so add 1 for actual month number
  • getDate() returns the day of the month (1-31)
  • getDay() returns the day of the week (0-6)
  • getTime() returns milliseconds since January 1, 1970

Format and Display Date Information

In this step, you'll learn various methods to format and display date information in JavaScript. Open the ~/project/dates.js file and add the following code to explore different formatting techniques:

// Create a current date object
let currentDate = new Date();

// Method 1: Using toLocaleDateString()
let localeDateString = currentDate.toLocaleDateString();
console.log("Local Date String:", localeDateString);

// Method 2: Using toDateString()
let dateString = currentDate.toDateString();
console.log("Date String:", dateString);

// Method 3: Using toLocaleString()
let localeString = currentDate.toLocaleString();
console.log("Locale String:", localeString);

// Method 4: Custom formatting
let customFormat =
  `${currentDate.getFullYear()}-` +
  `${(currentDate.getMonth() + 1).toString().padStart(2, "0")}-` +
  `${currentDate.getDate().toString().padStart(2, "0")}`;
console.log("Custom Format:", customFormat);

// Method 5: Internationalization API
let options = {
  weekday: "long",
  year: "numeric",
  month: "long",
  day: "numeric"
};
let intlFormat = currentDate.toLocaleDateString("en-US", options);
console.log("Internationalized Format:", intlFormat);

Example output:

Local Date String: 6/15/2023
Date String: Thu Jun 15 2023
Locale String: 6/15/2023, 12:30:45 PM
Custom Format: 2023-06-15
Internationalized Format: Thursday, June 15, 2023

Key points to remember:

  • toLocaleDateString() provides a localized date representation
  • toDateString() gives a human-readable date string
  • toLocaleString() includes both date and time
  • Custom formatting allows precise control over date display
  • Internationalization API offers advanced localization options

Modify Date Using Setter Methods

In this step, you'll learn how to modify date components using JavaScript's Date setter methods. Open the ~/project/dates.js file and add the following code to explore different ways of changing date values:

// Create a new Date object
let modifiableDate = new Date();
console.log("Original Date:", modifiableDate);

// Set specific year
modifiableDate.setFullYear(2024);
console.log("After setting year:", modifiableDate);

// Set month (0-11, so 5 represents June)
modifiableDate.setMonth(5);
console.log("After setting month:", modifiableDate);

// Set day of the month
modifiableDate.setDate(15);
console.log("After setting day:", modifiableDate);

// Set hours (0-23)
modifiableDate.setHours(14);
console.log("After setting hours:", modifiableDate);

// Set minutes (0-59)
modifiableDate.setMinutes(30);
console.log("After setting minutes:", modifiableDate);

// Set seconds (0-59)
modifiableDate.setSeconds(45);
console.log("After setting seconds:", modifiableDate);

// Chaining setter methods
let customDate = new Date();
customDate.setFullYear(2025).setMonth(11).setDate(31);
console.log("Custom Date:", customDate);

Example output:

Original Date: Thu Jun 15 2023 12:30:45 GMT+0000
After setting year: Thu Jun 15 2024 12:30:45 GMT+0000
After setting month: Thu Jun 15 2024 12:30:45 GMT+0000
After setting day: Sat Jun 15 2024 12:30:45 GMT+0000
After setting hours: Sat Jun 15 2024 14:30:45 GMT+0000
After setting minutes: Sat Jun 15 2024 14:30:45 GMT+0000
After setting seconds: Sat Jun 15 2024 14:30:45 GMT+0000
Custom Date: Wed Dec 31 2025 00:00:00 GMT+0000

Key points to remember:

  • Setter methods allow precise modification of date components
  • Months are zero-indexed (0-11)
  • Hours use 24-hour format (0-23)
  • Setter methods modify the original Date object
  • You can chain some setter methods for convenience

Perform Date Calculations

In this step, you'll learn how to perform various date calculations using JavaScript Date methods. Open the ~/project/dates.js file and add the following code to explore different date manipulation techniques:

// Create date objects for calculations
let currentDate = new Date();
let futureDate = new Date(currentDate.getTime());

// Add days to a date
futureDate.setDate(currentDate.getDate() + 30);
console.log("Current Date:", currentDate);
console.log("30 Days from Now:", futureDate);

// Calculate difference between dates
let differenceInMilliseconds = futureDate.getTime() - currentDate.getTime();
let differenceInDays = Math.floor(
  differenceInMilliseconds / (1000 * 60 * 60 * 24)
);
console.log("Days Between Dates:", differenceInDays);

// Calculate age or time elapsed
let birthDate = new Date("1990-01-01");
let ageInMilliseconds = currentDate.getTime() - birthDate.getTime();
let ageInYears = Math.floor(ageInMilliseconds / (1000 * 60 * 60 * 24 * 365.25));
console.log("Calculated Age:", ageInYears);

// Find the last day of the current month
let lastDayOfMonth = new Date(
  currentDate.getFullYear(),
  currentDate.getMonth() + 1,
  0
);
console.log("Last Day of Current Month:", lastDayOfMonth);

// Check if a year is a leap year
function isLeapYear(year) {
  return new Date(year, 1, 29).getMonth() === 1;
}
console.log("Is 2024 a Leap Year?", isLeapYear(2024));

Example output:

Current Date: Thu Jun 15 2023 12:30:45 GMT+0000
30 Days from Now: Sat Jul 15 2023 12:30:45 GMT+0000
Days Between Dates: 30
Calculated Age: 33
Last Day of Current Month: Wed Jun 30 2023 00:00:00 GMT+0000
Is 2024 a Leap Year? true

Key points to remember:

  • Use getTime() to get milliseconds for calculations
  • Convert milliseconds to days by dividing appropriately
  • You can add or subtract days using setDate()
  • Calculate age or time differences between dates
  • Check leap years by testing February 29th

Summary

In this lab, participants learned how to manipulate dates using JavaScript's Date object through a comprehensive exploration of date creation, retrieval, and manipulation techniques. The lab covered multiple approaches to initializing Date objects, including creating dates representing the current moment, specifying exact dates with parameters, parsing dates from strings, and generating dates from millisecond timestamps.

The practical exercises demonstrated key JavaScript date handling skills such as extracting specific date components, formatting date information, applying setter methods to modify dates, and performing date calculations. Participants gained hands-on experience with zero-indexed month representations, understanding different Date object initialization strategies, and leveraging built-in JavaScript methods to work effectively with temporal data across various programming scenarios.

Other CSS Tutorials you may like