JavaScript Date Object

Date object in JavaScript is a built-in object that allows us to work with dates and times conveniently. Using Date object, we can find out the current data and time, store own dates and times, perform calculations with these dates and convert dates into strings.

We can set and display a timer on the web page with the help of JavaScript date object. We can use various Date constructors to create instances of date object. It provides a lot of methods to set and get day, month, year, hour, minute and seconds. It has no properties.

JavaScript store the date as the number of milliseconds since midnight, January 1, 1970. This date is known as epoch.

JavaScript Date Constructor


JavaScript provides four different overloaded constructors to create instances of date object. They are as:

1. Date(): This constructor creates a new date object representing the current data and time belonging to the user’s system. It does not take any argument.

2. Date(milliseconds): This constructor creates a new date object with the specified number of milliseconds since 1 January 1970 at 00:00:00 GMT.

3. Date(dateString): This constructor creates a new date object with a string representing a date or a data and time.

4. Date(year, month, day, hours, minutes, seconds, milliseconds): This constructor creates an instance of date with the specified values separated by commas.

Different ways to create a Date object in JavaScript


Whenever we want to work with dates and times in JavaScript, then we need to create an instance of Date object. We can create a Date object using new keyword and some optional arguments in JavaScript.

It is the same as we create any other object in JavaScript. The general syntax for creating a Date object is as follows:

var myDate = new Date(Optional parameters);

Let’s see the different formats of creating Date object with initializing argument values.

1. First format:

var currentDate = new Date(); // passing no argument.

This is the most common format of Date object that JavaScript grabs the current date and time from the user’s computer and stores it into currentDate variable. We can create a date object by calling Date() constructor function.


2. Second format:

var myDate = new Date("July 30, 2022, 12:08:00"); // passing a simple date string to constructor.

This statement sets Date object with the specified month, day, and time as (month dd, yyyy, hh:mm:ss). If we omit it, then JavaScript sets it zero.

3. Third format:

var myBirthday = new Date(10, 08, 1992);

This statement creates a Date object with initializing the specified month, day, and year as(mm, dd, yyyy).

4. Fourth format:

var myDate = new Date(2022, 10, 30, 12, 33, 20, 30 );

This statement creates a Date object with initializing the specified year, month, day, hours, minutes, seconds, and milliseconds.

5. Fifth format:

var myDate = new Date(998550121000); // here, the argument is in milliseconds.

You can choose any of the above format, depending on which value you set as per requirement. If you do not use any argument, then JavaScript will store the current date in the object.

Getting PC’s Current Date and Time


Let’s create JavaScript program to display the user’s current date and time.

<script>
 var currentDate = new Date();
 console.log("Current date and time on PC: " +currentDate);
</script>
Output:
      Current date and time on PC: Sat Jul 30 2022 13:05:35 GMT+0530 (India Standard Time)

Argument used with JavaScript Date object


In this section, we have listed possible argument values associated with Date object in table form. They are as:

ArgumentPossible values
yyyyFour-digit integers
yyTwo-digit integers
monthFull month name from “January” to “December”
mth (month)Integers from 0 (Jan) to 11 (Dec)
dd (day of the month)Integers from 1 to 31
hh (hour of the day)Integers from 0 (midnight) to 23 (11:00 PM)
mm (minute of the hour)Integers from 0 to 59
ss (second of the minute)Integers from 0 to 59
ms (milliseconds of second)Integers from 0 to 999 second

Setting Date and Time of JavaScript Date object


JavaScript provides a variety of set methods to set date, or time in the Date object to facilitate. They are as follows:

1. setDate(): This method sets the day of the month for the specified date based on local time. The general syntax of this method to set the date of the month is as:

dateObj.setDate(dd); // dd is an integer from 1 to 31, representing day of month.
// For example:
   myDate.setDate(20);

Let’s take an example in which we will set the date of a month using setDate() method.

<script>
// Create an instance of date object.
   var day = new Date();
// Setting the date of a month.
   day.setDate(20);
   console.log(day);
</script>
Output:
      Wed Jul 20 2022 15:21:51 GMT+0530 (India Standard Time)

2. setMonth(): This method sets the month of the year for a specified date on the basis of local time. The general syntax to set the month of year is as:

dateObj.setMonth(mth);

Here, mth is the name of the month. It takes an integer between 0 to 11, starting with January (0), February (1) and so on.

Let’s take an example in which we will set the value of month using setMonth() method.

<script>
   var dateObj = new Date();
// Setting the month value.
   dateObj.setMonth(9);
   console.log(dateObj);
</script>
Output:
      Sun Oct 30 2022 15:45:51 GMT+0530 (India Standard Time)

3. setFullYear(): This month sets the year using full 4 digits (i.e. 2022) for the specified date on the basis of local time. The general syntax to set the year is as:

dateObj.setFullYear(yyyy);
// For example:
    dateObj.setFullYear(2022);

4. setTime(): This method sets the time by specifying the number of milliseconds (since 1 January 1970 00:00:00) on the basis of local time. The general syntax to set the time is:

dateObj.setTime(ms);
// For example:
    dateObj.setTime(20000);

5. setHours(): This method sets the hours property of Date object. The general syntax to set the hour of the day is as:

dateObj.setHours(hh);
// For example:
    dateObj.setHours(20);

6. setMinutes(): This method sets the mintues property of Date object. The general syntax to set the minute of the hour is as:

dateObj.setMinutes(mm);
// For example:
    dateObj.setMinutes(42);

7. setSeconds(): This method sets the seconds property of Date object. The general syntax to set the second of the minute is as:

dateObj.setSeconds(ss);
// For example:
    dateObj.setSeconds(59);

8. setMilliseconds(): This method sets the milliseconds property of Date object. The general syntax to set the millisecond of the second is as:

dateObj.setMilliseconds(ms);
// For example:
    dateObj.setMilliseconds(988);

Example: Setting Year, Month, Day, and Time


Let’s take an example program in which we will set year, month, day, hour, minute, second, and milliseconds on the basis of local time and display it on the web browser.

<script>
   var dateObj = new Date();
// Setting the year, month, and day values.
   dateObj.setYear(2022);
   dateObj.setMonth(9);
   dateObj.setDate(8);

// Setting hour, minute, second, and milliseconds values.
   dateObj.setHours(05);
   dateObj.setMinutes(45);
   dateObj.setSeconds(35);
   dateObj.setMilliseconds(555);
   console.log(dateObj);
</script>
Output:
      Sat Oct 08 2022 05:45:35 GMT+0530 (India Standard Time)

Note: We can only set the date and time properties inside the Date object with these methods. JavaScript does not provide any method to change the system date and time of the computer on which the web browser is running.

Getting Date and Time from JavaScript Date object


JavaScript provides many get methods to get (or read) values from a Date object. Let’s understand about these get methods with a brief description.

1. getDate(): This method returns the day of the month for the specified date on the basis of local time. It returns an integer value between 1 and 31 that represents the day for the specified date. The general syntax to get the day of the month is as:

dateObj.getDate();

Let’s take an example program in which we will display today’s date.

<script>
  var dateObj = new Date();
  console.log("Today's day: " +dateObj.getDate());
</script>
Output:
      Today's day: 31

Let’s take an example to print the day from the specified date in the Date() constructor function.

<script>
var dateObj = new Date("August 15, 1947 20:22:10");
console.log(dateObj.getDate());
</script>
Output:
      15

2. getDay(): This method returns the day of the week for the specified date on the basis of local time. It returns an integer value between 0 and 6 that represents days of the week for the specified date. For example, 0 represents Sunday, 1 represents Monday, and so on.

The general syntax to get day of the week is as:

dateObj.getDay();

Let’s take an example program in which we will print the value of today’s weekday.

<script>
var dateObj = new Date();
console.log("Today's weekday: " +dateObj.getDay());
</script>
Output:
      0 (representing Sunday)

Converting getDay() into a Day name


Let’s take an example program in which we will get the name of day from a getDay() value using an array.

<script>
// Creating an array object with initializing value 7.
   let day_names = new Array(7);
   day_names[0] = "Sunday";
   day_names[1] = "Monday";
   day_names[2] = "Tuesday";
   day_names[3] = "Wednesday";
   day_names[4] = "Thursday";
   day_names[5] = "Friday";
   day_names[6] = "Saturday";

   let dateObj = new Date("August 15, 1947 20:22:10");
   let day_now = dateObj.getDay();
   console.log("Name of day on 15 Aug 1947: " +day_names[day_now]);
</script>
Output:
      Name of day on 15 Aug 1947: Friday

3. getMonth(): This method returns the month of the year for the specified date according to local time. The value returned by getMonth() method is an integer between 0 and 11. Here, 0 represents January, 1 to February, and so on.

The general syntax to get the month of the year is as:

dateObj.getMonth();

Let’s take an example in which we will print the current month.

<script>
  var dateObj = new Date();
  console.log("Current month: " +dateObj.getMonth());
</script>
Output:
      Current month: 6

Converting getMonth() into a Month Name


There are two ways to convert getMonth() into a month name that are as:

  • Using an array
  • Using a function

Example: Using Array to return the name of month

<script>
// Create an array object named month_names of size 12.
   let month_names = new Array(12);
   month_names[0] = "January";
   month_names[1] = "February";
   month_names[2] = "March";
   month_names[3] = "April";
   month_names[4] = "May";
   month_names[5] = "June";
   month_names[6] = "July";
   month_names[7] = "August";
   month_names[8] = "September";
   month_names[9] = "October";
   month_names[10] = "November";
   month_names[11] = "December";

// Create a Date object.
   let dateObj = new Date(1992, 09, 08);
   let monthName = dateObj.getMonth();
   console.log("Name of month: " +month_names[monthName]);
</script>
Output:
      Name of month: October

Example: Using a function to retun the name of month

<script>
// Create a function named monthName with one parameter.
   function monthName(monthValue) {
   switch(monthValue) {
     case 0 : return "January";
     case 1 : return "February";
     case 2 : return "March";
     case 3 : return "April";
     case 4 : return "May";
     case 5 : return "June";
     case 6 : return "July";
     case 7 : return "August";
     case 8 : return "September";
     case 9 : return "October";
     case 10 : return "November";
     case 11 : return "December";
    }
  }
// Create a Date object.
   let dateObj = new Date(1992, 11, 08);
   let mth = dateObj.getMonth();
   console.log("Name of month: " +monthName(mth));
</script>
Output:
     Name of month: December

In this example, we have passed the getMonth() value as an argument to the monthName() function. Then, a switch() statement uses it to evaluate the value and return the exact string.


4. getFullYear(): This method returns a year as four digits (2021, 2022, etc) for the specified date according to local time. The general syntax to get year is as:

dateObj.getFullYear();

Let us take an example program to print the value of the current year according to local time.

<script>
  let dateObj = new Date();
  let yearValue = dateObj.getFullYear();
  console.log("Current Year: " +yearValue);

  let dateObj2 = new Date("December 31, 2022 20:22:10 GMT+11:00");
  let dateObj3 = new Date("December 31, 2022 20:22:10 GMT-11:00");
  console.log("Year1: " +dateObj2.getFullYear());
  console.log("Year2: " +dateObj3.getFullYear());
</script>
Output:
      Current Year: 2022
      Year1: 2022
      Year2: 2023

5. getHours(): This method returns the hour property (from 0 (midnight) to 23 (11:00 PM))) of the specified Date object according to local time. The general syntax to get an hour of the day is as:

dateObj.getHours();

6. getMintues(): This method returns the minute property (from 0 to 59) of the specified Date object according to local time. The general syntax is as:

dateObj.getMinutes();

7. getSeconds(): This method returns the second property (from 0 to 59) of the specified Date object on the basis of local time. The general syntax is as:

dateObj.getSeconds();

8. getMilliseconds(): This method returns the milliseconds property (from 0 to 999) of the specified Date object on the basis of local time. The general syntax is as:

dateObj.getMilliseconds();

9. getTime(): This method returns the numeric value associated with the time of a specified Date object on the basis of local time. The value returned by getTime() method is the number of milliseconds since January 1, 1970 GMT. The general syntax is as:

dateObj.getTime();

In this tutorial, you learned JavaScript Date object and its different methods with many example programs. Hope that you will have understood how to set and get date and time from a Date object.
Thanks for reading!!!