Master JavaScript Programming From Scratch

Clear, interactive, and structured JavaScript lessons designed for absolute beginners.

Date & Time in JavaScript

JavaScript provides the built-in Date object for working with dates and time.

Using the Date object, we can get the current date and time, extract individual date values, and format dates for applications.

What is the Date Object?

The Date object represents a single moment in time. JavaScript uses the Date object to work with year, month, day, hour, minute and second values.

Simple Definition

The Date object is a built-in JavaScript object used to create, read and manipulate date and time values.

Working with Date Object
new Date()
→
Date Object
→
getDate()
→
getMonth()
JavaScript Date Object

JavaScript Date object is used to work with date and time values.

Creating a Date Object

We can create a Date object using the new Date() constructor.

var today = new Date();

    console.log(today);
Output:
Current date and time

Example 1: Get Current Date

The following example creates a Date object and displays the current date.

var today = new Date();

    console.log(today.toDateString());
Output:
Current date

Example 2: Get Date Parts

JavaScript provides methods such as getFullYear(), getMonth() and getDate() to get individual date values.

var today = new Date();

    var year = today.getFullYear();
    var month = today.getMonth() + 1;
    var day = today.getDate();

    console.log(year);
    console.log(month);
    console.log(day);
Output:
Current Year
Current Month
Current Day

Example 3: Create a Specific Date

We can also create a Date object with a specific date.

var birthday = new Date("1995-05-15");

    console.log(birthday.toDateString());
Output:
Mon May 15 1995

Common Date Methods

getFullYear() – Returns the year.

getMonth() – Returns the month from 0 to 11.

getDate() – Returns the day of the month.

getDay() – Returns the day of the week from 0 to 6.

getHours() – Returns the hour.

getMinutes() – Returns the minutes.

Important Points

• JavaScript uses the Date object for date and time operations.

• new Date() creates a Date object.

• getMonth() returns values from 0 to 11.

• getDate() returns the day of the month.

• getFullYear() returns the four-digit year.

• Date values can be formatted using different Date methods.

Summary

The JavaScript Date object allows us to work with dates and time. We can create dates, retrieve date components and format dates using built-in Date methods.