JavaScript Dates

What is the JavaScript Date Object?

The Date object in JavaScript is used to work with dates and times. It provides methods to create, manipulate and format date and time values. The Date object can represent any point in time down to milliseconds since January 1, 1970 (UTC), also known as the Unix Epoch.

Creating a Date Object

There are multiple ways to create a Date object in JavaScript:

1. Create a Date Object for the Current Date and Time

const currentDate = new Date();
console.log(currentDate); // Example output: Mon Nov 25 2024 12:34:56 GMT+0530 (IST)

2. Create a Date Object Using a Specific Date String

const specificDate = new Date("2024-11-25");
console.log(specificDate); // Output: Mon Nov 25 2024 00:00:00 GMT+0530 (IST)

3. Create a Date Object Using Year, Month, Day and More

const customDate = new Date(2024, 10, 25, 12, 30, 45); // Note: Months are 0-based (0 = January, 11 = December)
console.log(customDate); // Output: Mon Nov 25 2024 12:30:45 GMT+0530 (IST)

4. Create a Date Object Using Timestamps

const timestampDate = new Date(1700000000000); // Milliseconds since Unix Epoch
console.log(timestampDate); // Output: Fri Nov 15 2024 14:53:20 GMT+0530 (IST)

Getting Date and Time Components

JavaScript provides methods to retrieve specific parts of a date.

Common Methods:

  1. Get Full Year
const date = new Date();
console.log(date.getFullYear()); // Output: 2024
  1. Get Month (0-based index: 0 = January, 11 = December)
console.log(date.getMonth()); // Output: 10 (November)
  1. Get Date (Day of the Month)
console.log(date.getDate()); // Output: 25
  1. Get Day of the Week (0 = Sunday, 6 = Saturday)
console.log(date.getDay()); // Output: 1 (Monday)
  1. Get Hours, Minutes, Seconds, Milliseconds
console.log(date.getHours()); // Output: Current hour
console.log(date.getMinutes()); // Output: Current minutes
console.log(date.getSeconds()); // Output: Current seconds
console.log(date.getMilliseconds()); // Output: Current milliseconds
  1. Get Time in Milliseconds Since Unix Epoch
console.log(date.getTime()); // Example output: 1732661096567

Setting Date and Time Components

You can also modify a date object using setter methods.

Examples:

  1. Set Full Year
const date = new Date();
date.setFullYear(2030);
console.log(date); // Year updated to 2030
  1. Set Month
date.setMonth(5); // Sets month to June (0-based)
console.log(date);
  1. Set Date (Day of the Month)
date.setDate(15); // Sets day to 15th
console.log(date);
  1. Set Hours, Minutes, Seconds and Milliseconds
date.setHours(10);
date.setMinutes(45);
date.setSeconds(30);
date.setMilliseconds(500);
console.log(date);

Formatting Dates

JavaScript does not provide robust built-in date formatting methods. However, you can use these techniques:

Using toLocaleDateString()

const date = new Date();
console.log(date.toLocaleDateString("en-US")); // Output: 11/25/2024

Using toLocaleTimeString()

console.log(date.toLocaleTimeString("en-US")); // Output: 12:34:56 PM

Using toISOString()

console.log(date.toISOString()); // Output: 2024-11-25T07:04:56.567Z

Comparing Dates

You can compare dates using comparison operators.

const date1 = new Date("2024-11-25");
const date2 = new Date("2024-11-26");

console.log(date1 < date2); // Output: true
console.log(date1.getTime() === date2.getTime()); // Output: false

Calculating Time Differences

You can calculate the difference between two dates in milliseconds.

const startDate = new Date("2024-11-25");
const endDate = new Date("2024-12-01");

const difference = endDate - startDate; // Difference in milliseconds
const daysDifference = difference / (1000 * 60 * 60 * 24);
console.log(daysDifference); // Output: 6

Common Use Cases for JavaScript Dates

  1. Displaying Current Date and Time on a Website
const now = new Date();
document.getElementById("dateTime").innerText = now.toLocaleString();
  1. Calculating Age from Birthdate
function calculateAge(birthdate) {
const today = new Date();
const birth = new Date(birthdate);
let age = today.getFullYear() - birth.getFullYear();
const monthDiff = today.getMonth() - birth.getMonth();
if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
age--;
}
return age;
}

console.log(calculateAge("2000-05-15")); // Output: Age in years
  1. Countdown Timer
function countdown(targetDate) {
const now = new Date();
const target = new Date(targetDate);
const difference = target - now;
if (difference <= 0) {
console.log("Countdown complete!");
return;
}
const days = Math.floor(difference / (1000 * 60 * 60 * 24));
console.log(`${days} days left`);
}

countdown("2024-12-31");

Leave a Comment