Date

JavaScript Date Tutorial

Table of Contents

  1. Introduction to JavaScript Date

  2. Creating Dates in JavaScript

    • Using new Date()

    • Creating Date with String Format

    • Creating Date with Date and Time Components

    • Creating Date with Timestamps

  3. Date Methods

    • Getting Date Components

      • getFullYear()

      • getMonth()

      • getDate()

      • getDay()

    • Getting Time Components

      • getHours()

      • getMinutes()

      • getSeconds()

      • getMilliseconds()

    • Setting Date and Time Components

      • setFullYear()

      • setMonth()

      • setDate()

      • setHours()

      • setMinutes()

      • setSeconds()

      • setMilliseconds()

  4. Formatting Dates

    • Using toDateString()

    • Using toLocaleDateString()

    • Using toISOString()

    • Using toLocaleTimeString()

  5. Working with Time Zones

    • Getting UTC Date and Time

    • Getting Timezone Offset

  6. Comparing Dates

    • Using Relational Operators

    • Using getTime() Method

  7. Date Calculations

    • Adding/Subtracting Days

    • Finding Difference Between Dates

  8. Conclusion


1. Introduction to JavaScript Date

Welcome to the Codes with Pankaj tutorial on JavaScript Date! In this tutorial, we will explore how to work with dates and times in JavaScript. By the end of this tutorial, you’ll be able to create, manipulate, and format dates with ease. Let’s get started!

JavaScript provides a built-in Date object that allows you to work with dates and times. The Date object is powerful and versatile, letting you perform various operations like getting the current date, formatting dates, and performing date calculations.

2. Creating Dates in JavaScript

There are several ways to create dates in JavaScript.

Using new Date()

The simplest way to create a new date is by using the new Date() constructor without any arguments. This will create a date object with the current date and time.

Example:

let currentDate = new Date();
console.log(currentDate);

Creating Date with String Format

You can create a date by passing a date string to the Date constructor.

Example:

let dateString = new Date("August 17, 2024");
console.log(dateString);

Creating Date with Date and Time Components

You can specify the year, month, day, hours, minutes, seconds, and milliseconds when creating a date.

Example:

let specificDate = new Date(2024, 7, 17, 10, 30, 0);
console.log(specificDate);

Creating Date with Timestamps

You can create a date by passing the number of milliseconds since January 1, 1970 (known as the Unix Epoch).

Example:

let timestampDate = new Date(1609459200000);
console.log(timestampDate);

3. Date Methods

Getting Date Components

getFullYear()

This method returns the year of the specified date.

let year = currentDate.getFullYear();
console.log(year);  // Output: 2024

getMonth()

This method returns the month of the specified date (0-11).

let month = currentDate.getMonth();
console.log(month);  // Output: 7 (August, as months are zero-indexed)

getDate()

This method returns the day of the month (1-31).

let day = currentDate.getDate();
console.log(day);  // Output: 17

getDay()

This method returns the day of the week (0-6, where 0 is Sunday).

let dayOfWeek = currentDate.getDay();
console.log(dayOfWeek);  // Output: 6 (Saturday)

Getting Time Components

getHours()

This method returns the hour of the specified date (0-23).

let hours = currentDate.getHours();
console.log(hours);  // Output: 10

getMinutes()

This method returns the minutes (0-59).

let minutes = currentDate.getMinutes();
console.log(minutes);  // Output: 30

getSeconds()

This method returns the seconds (0-59).

let seconds = currentDate.getSeconds();
console.log(seconds);

getMilliseconds()

This method returns the milliseconds (0-999).

let milliseconds = currentDate.getMilliseconds();
console.log(milliseconds);

Setting Date and Time Components

You can also modify the date and time using setter methods.

setFullYear()

Sets the year.

currentDate.setFullYear(2025);
console.log(currentDate);

setMonth()

Sets the month.

currentDate.setMonth(0);  // January
console.log(currentDate);

setDate()

Sets the day of the month.

currentDate.setDate(15);
console.log(currentDate);

setHours()

Sets the hour.

currentDate.setHours(12);
console.log(currentDate);

setMinutes()

Sets the minutes.

currentDate.setMinutes(45);
console.log(currentDate);

setSeconds()

Sets the seconds.

currentDate.setSeconds(30);
console.log(currentDate);

setMilliseconds()

Sets the milliseconds.

currentDate.setMilliseconds(500);
console.log(currentDate);

4. Formatting Dates

JavaScript provides several methods to format dates as strings.

Using toDateString()

Returns the date in a human-readable format.

console.log(currentDate.toDateString());  // Output: Sat Jan 15 2025

Using toLocaleDateString()

Returns the date in a format based on the local region.

console.log(currentDate.toLocaleDateString());  // Output: 1/15/2025 (in the US locale)

Using toISOString()

Returns the date in ISO format (YYYY-MM-DDTHH:mm:ss.sssZ).

console.log(currentDate.toISOString());

Using toLocaleTimeString()

Returns the time in a format based on the local region.

console.log(currentDate.toLocaleTimeString());

5. Working with Time Zones

JavaScript Date objects work with the local time zone by default, but you can also work with UTC (Coordinated Universal Time).

Getting UTC Date and Time

You can retrieve the UTC components using methods like getUTCFullYear(), getUTCMonth(), etc.

Example:

console.log(currentDate.getUTCFullYear());

Getting Timezone Offset

You can get the difference between UTC time and local time in minutes using getTimezoneOffset().

Example:

console.log(currentDate.getTimezoneOffset());

6. Comparing Dates

Using Relational Operators

You can compare two dates using relational operators like <, >, <=, >=.

Example:

let date1 = new Date("2024-08-17");
let date2 = new Date("2024-08-18");

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

Using getTime() Method

You can compare dates by converting them to timestamps using getTime().

Example:

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

7. Date Calculations

Adding/Subtracting Days

To add or subtract days from a date, you can manipulate the day component.

Example:

let tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
console.log(tomorrow);

Finding Difference Between Dates

You can find the difference between two dates by subtracting their timestamps.

Example:

let diffInTime = date2.getTime() - date1.getTime();
let diffInDays = diffInTime / (1000 * 3600 * 24);
console.log(diffInDays);  // Output: 1

8. Conclusion

In this detailed tutorial, we've covered the basics of working with dates and times in JavaScript. From creating dates to formatting and performing date calculations, you now have the tools to manage dates in your JavaScript projects.

For more tutorials and examples, visit www.codeswithpankaj.com! Happy coding!


Last updated