Physical Address

Sagipora Sopore Baramulla 193201  Jammu & Kashmir

featured image

How To Use JavaScript Date() Object, Fast and Easy

Working with JavaScript Date() object can sometimes become tidy. There are a lot of methods you can work with. And also the enormous amount of date and time formats add to problems. But the whole scenario goes down to the JavaScript Date() object basics. If you want to get to grips with JavaScript date and time, you need to understand the basics clearly. In this tutorial, you will know everything from basics to advance and in the end master the whole cluster of concepts related to JavaScript Date().

Increase Your IT Knowledge with Practice Test Exam Dumps from ExamLab

Table of contents:

  • What is JavaScript Date() object?
    • Date() constructor.
    • How to create JavaScript Date object
    • JavaScript Date Methods:
  • 1) How to convert JavaScript date to a string?
  • 2) How to convert a JavaScript date object to a UTCString?
  • 3) How to convert JavaScript date to an ISO string?
  • 4 How to parse date in JavaScript?
  • 5) JavaScript date get methods?
  • 6) Date set-methods in JavaScript?
  • 7) How to compare two date objects in JavaScript?
  • 8) How to add days to a JavaScript date?
  • 8) How to get max date(most recent date) in an array of date objects?
  • 9) How to sort a date array in JavaScript?
  • 10) How to set timezone offset using JavaScript ?
  • 11) How to convert date to a JSON object?
  • 12) Get date in locale from a JS date object?
  • 13) Get time in locale from a JS date object?
  • 14) Get date and time in locale from a JS date object?

What is JavaScript Date() object?

In JavaScript, the date object is used to work with date and time. The date object in JavaScript is created with the new Date() syntax. JavaScript Date() object is a standard way to work with the date and time in JavaScript. It includes a constructor and a good number of methods that make working with date and time easy.

Date() constructor.

Javascript date constructor creates a Date instance that represents a time in a platform-independent format. The Date object contains a property that represents the number of milliseconds passed since 1 January 1970 UTC.

How to create JavaScript Date object?

There are four ways to create a date object in JavaScript. All of these are created with the Date() constructor using the syntax

new Date(arguments);

These are as follows

1) new Date():

The new Date() constructor with empty arguments creates a date in your local format. It automatically gets your local time zone from the browser.

Syntax:
new Date();
Result:
Mon Mar 07 2022 23:51:22 GMT+0530 (India Standard Time)

2) new Date(year, month,..):

This syntax takes multiple arguments. It also gets your local time zone automatically. It takes the year, month, day, hours, minutes, seconds, and milliseconds as arguments. All of these arguments are not necessary as you will see in the next few examples. But it’s important to provide a minimum of two arguments year and month. If only one argument is passed that will be a different date object. You’ll learn about it in the next date() object type.

a) Syntax:
// new Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date(2015, 2, 25, 14, 22, 12, 33);

In the above example, we pass 7 arguments, which is essentially the maximum number of arguments it can take. It results in the following date format.

Result:
Wed Mar 25 2015 14:22:12 GMT+0530 (India Standard Time)
b) Syntax:
// new Date(year, month, day, hours, minutes, seconds)
new Date(2015, 2, 25, 14, 22, 12);

The date objects declared with the above syntax display the date in the same format as in the first syntax. But it should be noted that it takes only six arguments as compared to the first syntax which takes 7 arguments. The millisecond argument is omitted in this syntax.

Result:
Wed Mar 25 2015 14:22:12 GMT+0530 (India Standard Time)
c) Syntax:
// new Date(year, month, day, hours, minutes)
new Date(2015, 2, 25, 14, 22);

The above syntax takes only five arguments. Seconds and milliseconds are omitted. Also, there is a difference in the output as well.

Result:
Wed Mar 25 2015 14:22:00 GMT+0530 (India Standard Time)

As compared to the above syntax, it displays two zeroes instead of the seconds since seconds are not passed as arguments.

d) Syntax:
// new Date(year, month, day, hours)
new Date(2015, 2, 25, 14);
Result:
Wed Mar 25 2015 14:00:00 GMT+0530 (India Standard Time)

This is similar to the above syntax. Since we don’t pass minutes and seconds, it displays two zeroes.

e) Syntax:
// new Date(year, month, day);
new Date(2015, 2, 25);
Result:
Wed Mar 25 2015 00:00:00 GMT+0530 (India Standard Time)
f) Syntax:
// new Date(year, month);
new Date(2015, 2);
Result:
Wed Mar 25 0000 00:00:00 GMT+0530 (India Standard Time)

Note: This syntax takes a minimum of two arguments. If we pass less than two arguments then that is a different syntax. Which we will see next.

Also read: Convert Array to String in JavaScript – 4 Easy Methods

3) new Date(milliseconds):

The new Date(milliseconds) takes a single argument milliseconds. It creates a date as the number of milliseconds passed since Thu Jan 01, 1970. For example

// new Date(milliseconds)
new Date(0);

In the above example, we pass 0 as an argument. I will display 0 seconds passed since Jan 01, 1970. The result of this Date object is

Thu Jan 01 1970 05:30:00 GMT+0530 (India Standard Time)

Let’s take another example where we pass 1000 milliseconds to the Date() constructor. 1000 milliseconds is 1 second, so we expect the above date to increase by 1 second.

new Date(1000)
Result:
Thu Jan 01 1970 05:30:01 GMT+0530 (India Standard Time)

4) new Date(dateString):

This date object syntax takes a string as an argument. The dateString is determined by the type of date standard. This syntax mainly takes three types of inputs. These are as follows

a) Javascript long dates:

The syntax of long dates is usually MMM DD YYYY. But the order may differ in other syntaxes.

JavaScript long date format examples:

new Date("October 25 1998");
new Date("25 Oct 1998");
new Date("Oct 25 1998");
new Date("OCTOBER, 25, 1998");

The results of the above examples are

Sun Oct 25 1998 00:00:00 GMT+0530 (India Standard Time)
Sun Oct 25 1998 00:00:00 GMT+0530 (India Standard Time)
Sun Oct 25 1998 00:00:00 GMT+0530 (India Standard Time)
Sun Oct 25 1998 00:00:00 GMT+0530 (India Standard Time)

The result of all these examples is the same. The only difference is that we pass different date strings to them. Also, it must be noted that these strings are type sensitive and commas are not mandatory.

b) JavaScript Short date strings:

JavaScript short date strings are usually of the form MM/DD/YYYY.

JavaScript short date example:

date = new Date("10/25/1998"); 

The above date object will result in the following date format

Sun Oct 25 1998 00:00:00 GMT+0530 (India Standard Time)
c) ISO dates in JavaScript:

ISO stands for an international standard for the representation of dates and times. In other words, it’s an international standard syntax or way to represent dates. It’s the preferred date syntax in JavaScript.

JavaScript ISO date examples:

new Date("2018-05-15"); // YEAR-MONTH-DAY
new Date("2019-07"); // YEAR-MONTH ONLY
new Date("2013"); // YEAR-ONLY
new Date("2017-03-27T12:00:00Z"); 
// YEAR-MONTH-DAY T HOURS:MINUTES:SECONDS

OUTPUT:

Tue May 15 2018 05:30:00 GMT+0530 (India Standard Time)
Mon Jul 01 2019 05:30:00 GMT+0530 (India Standard Time)
Tue Jan 01 2013 05:30:00 GMT+0530 (India Standard Time)
Mon Mar 27 2017 17:30:00 GMT+0530 (India Standard Time)

JavaScript Date Methods:

1) How to convert JavaScript date to a string?

To convert a JavaScript date object to a string we use the Object.toString() method. This method returns a string and we can use it in the HTML then.

Date.toString example:

const date = new Date();
const dateString = date.toString();

Output:

Fri Mar 11 2022 00:16:04 GMT+0530 (India Standard Time)
Fri Mar 11 2022 00:16:04 GMT+0530 (India Standard Time)

Although it seems they output the same thing, under the hood they are different. Let’s first check the types of these two constants.

console.log(typeof date);
console.log(typeof dateString);

Result:

object
string

Thus, the above results clarify that the date constant is a date object while the dateString constant is a string.

The typeof checks the type of the variable.

There is another method to convert JavaScript date object to a string. It’s the .toDateString() method. The .toDateString() method converts the date object to a more readable date string. Also, it omits the time and only displays the date.

Example of .toDateString() method:

const date = new Date();
console.log(date.toDateString());

The result of the above code block is:

Fri Mar 11 2022

Also read: What is Call Stack In Javascript And Why Its Important

2) How to convert a JavaScript date object to a UTCString?

To convert a JavaScript date object to a UTCString we use the .toUTCString() method.

UTC stands for Coordinated Universal Time and it’s a date display standard.

UTCString method example:

const date = new Date();
console.log(date.toUTCString());

The code results in the following output:

Fri, 11 Mar 2022 18:10:03 GMT

3) How to convert JavaScript date to an ISO string?

To convert a JavaScript date object to an ISO string, we use the .toISOString() method. It converts the date object to a string according to the ISO standard.

Example of toISOString() method?

const date = new Date();
console.log(date.toISOString()):

The result of the above code is :

2022-03-11T18:21:54.579Z

4 How to parse date in JavaScript?

If we have a valid date string and want to convert it into a date object, we use the static method Date.parse() and new Date(milliseconds).

The Date.parse() method accepts a string parameter and returns the number of milliseconds between the date string and 1 Jan 1970. Now, you can use these milliseconds to create a date object.

Example of parsing date in JavaScript?

const milliseconds = Date.parse("October 25, 1998");
const date = new Date(milliseconds);
console.log(milliseconds);
console.log(date)

The result of the above code is :

909253800000
Sun Oct 25 1998 00:00:00 GMT+0530 (India Standard Time)

5) JavaScript date get methods?

a) Date.now();

To get the number of milliseconds since midnight 1 Jan 1970, we use the Date.now() method. Date.now() is a static method and can not be used on a date object.

Example:

console.log(Date.now());

Result:

1647025358563

b) .getDate();

The .getDate() is used to get the day of the month.

Example:

const date = new Date();
const date = date.getDate();
console.log(date);

Result:

12

c) .getDay();

To get the day of the week, we use the .getDay() method.

Example:

const date = new Date();
const dayOfTheWeek = date.getDay();
console.log(dayOfTheWeek);

Result:

6

d) .getFullYear();

To get the year out of a date object, we use the .getFullYear() method. The .getFullYear() method returns the year like 2018, 2019 etc

Example:

const date = new Date();
const year = date.getFullYear();
console.log(year);

Result:

2022

e) .getHours();

In order to get Hours, the .getHours() method is used. For example,

Example:

const date = new Date();
const hours = date.hours();
console.log(hours);

Result:

0

f) .getMinutes();

The .getMinutes() returns the minutes from a date object, for example,

Example:

const date = new Date();
const minutes = date.getMinutes();
console.log(minutes);

Result:

47

g) .getMonth();

In order to get the month from a date object, we use the .getMonth() method, for example.

Example:

const date = new Date();
const month= date.getMonth();
console.log(month);

Result:

2 // March

It should be noted that JavaScript months are zero-based. In simpler terms, they start from 0, and by zero we mean Jan, and by 1 we mean Feb. Same is true for other months as well.

h) .getSeconds();

To get the seconds from a JavaScript date object, we use the .getSeconds() method, for example

Example:

const date = new Date();
const seconds = date.getSeconds();
console.log(seconds);

Result:

45

i) .getMilliseconds();

The .getMilliseconds() method is used to get milliseconds from a date object. for example.

Example:

const date = new Date();
const milliseconds = date.getMilliseconds();
console.log(milliseconds);

Result:

35

Note: JavaScript Date.now() and .getMilliseconds() are two different methods. Date.now() return the number of milliSeconds passed since midnight 1Jan 1970 while .getMilliseconds() return the miiliseconds from a date object.

6) Date set-methods in JavaScript?

a) .setDate()

The .setDate() method sets the date of the month of a JavaScript date object, for example

Example:

const date = new Date();
console.log(new Date(date.setDate(2049)));

The .setDate() method returns milliseconds. We pass these milliseconds to a new Date() constructor to get a date object.

The above code results in the following output

Sat Mar 05 2022 23:45:29 GMT+0530 (India Standard Time)

It should be noted that JavaScript months are zero-based so 1 means Jan and so on.

Also, if a number greater than the last day of the month is passed, it will not result in an error. But will simply increment the month.

b) .setFullYear()

The .setFullYear() method sets the year of a JavaScript date object, for example

Example:

const date = new Date();
console.log(new Date(date.setFullYear(2049)));

The above code results in the following output

Sat Mar 05 2049 23:45:29 GMT+0530 (India Standard Time)

c) .setMonth()

The .setMonth() method sets the month of a JavaScript date object, for example

Example:

const date = new Date();
console.log(new Date(date.setMonth(10)));

The above code results in the following output

Sat November 05 2049 23:45:29 GMT+0530 (India Standard Time)

It should be noted that JavaScript months are zero-based so 01 means Jan and so on.

Also, if a number greater than 11 is passed to the .setMonth() method, it will not result in an error. But will simply increment the year.

d) .setHours()

The .setHours() method sets the hours of a JavaScript date object, for example

Example:

const date = new Date();
console.log(new Date(date.setHours(10)));

The above code results in the following output

Sat November 05 2049 10:45:29 GMT+0530 (India Standard Time)

Also read: Reactjs best practices 2022, code this not that

e) .setMinutes()

The .setMinutes() method sets the minutes of a JavaScript date object, for example

Example:

const date = new Date();
console.log(new Date(date.setMinutes(10)));

The above code results in the following output

Sat November 05 2049 23:10:29 GMT+0530 (India Standard Time)

f) .setSeconds()

The .setSeconds() method sets the seconds of a JavaScript date object, for example

Example:

const date = new Date();
console.log(new Date(date.setSeconds(30)));

The above code results in the following output

Sat November 05 2049 23:45:30 GMT+0530 (India Standard Time)

7) How to compare two date objects in JavaScript?

To compare two date objects in JavaScript, follow these steps

Let’s take an example where we compare two dates today and a date in the past.

const date1 = new Date();
const date2 = new Date(2015, 2, 25, 14, 22, 12, 33);

We will now use the .getTime() method to get the number of milliseconds for both date objects.

const date1Milli = date1.getTime();
const date2Milli = date2.getTime();

Lastly, let’s compare the milliseconds.

if(date1Milli > date2Milli) {
console.log("date1 is a more recent date");
} else {
console.log("date2 is a more recent date");
}

The result of the above code block is

"date1 is a more recent date"

The date1 is a more recent date

The .getTime() method returns the number of milliseconds passed since 1 Jan 1970. The greater the number of milliseconds the more recent date.

Try comparing two date objects in JavaScript on Codepen:

See the Pen compare two date objects in JavaScript by nadeem (@nasyxnadeem) on CodePen.

8) How to add days to a JavaScript date?

Firstly, create a date object.

const date = new Date();

Now, get the day of the month using the .getDate() method.

const getDay = date.getDate();

Use the .setDate() method to set the day of the month to the new day. Here we add 1 day to the date. You can add the number of days as per your requirement.

const newDateinMillis = date.setDate(getDay + 1);

The .setDate() method returns the number of milliseconds passed since 1 Jan 1970 we need to convert it back to a date object. So, we use new Date(milliseconds) constructor to create a new date out of it.

const newDate = new Date(newDateinMillis);

Try adding days to a JavaScript date on Codepen:

See the Pen add days to a JavaScript date by nadeem (@nasyxnadeem) on CodePen.

8) How to get max date(most recent date) in an array of date objects?

If you have an array of dates and want to get the most recent date or max date out of it. Here is the example where we get the max date out of an array of dates.

Step 1: Create a date array.

const date = new Date();
const date2 = new Date(1998, 3, 25);
const date3 = new Date(2003, 3, 25);
const date4 = new Date(2007, 3, 25);

const dateArr = [date, date2, date3, date4];

Now, to get the most recent date we first loop over the array using the map() function.

And get the number of milliseconds passed since 1 Jan 1970 using the .getTime() function for each date entry.

dateArr.map(a=> a.getTime()

Since the map() function return an array of milliseconds, we spread the date array by using the spread(…) operator.

Read more about the map() method here, JavaScript Higher Order Functions Simplified – map(), reduce() and filter()

(...dateArr.map(a=> a.getTime())

Now, using the Math.max() function we get the max milliseconds.

Math.max(...dateArr.map(a=> a.getTime()))

Finally, we pass the milliseconds to the date constructor to get the date object.

const maxDate = new Date(Math.max(...dateArr.map(a=> a.getTime())));

Try getting max date(most recent date) in an array of date objects on Codepen:

See the Pen get max date(most recent date) in an array of JavaScript date objects by nadeem (@nasyxnadeem) on CodePen.

9) How to sort a date array in JavaScript?

Let’s take an example to sort the date array given below.

const date = new Date();
const date2 = new Date(1998, 3, 25);
const date3 = new Date(2003, 3, 25);
const date4 = new Date(2007, 3, 25);
const dateArr = [date, date2, date3, date4];

a) In descending order:

Let’s first sort the above date array in descending order. By descending order we mean the most recent date will become the first date and so on.

const sortedArr = dateArr.sort((a, b) => b.getTime() - a.getTime());

In the above example, we use the sort method to sort the array and in the callback function, we convert the date entries to milliseconds using the .getTime() method.

It should be noted that the sortedArr contains milliseconds and not the actual date objects. To convert it back to date objects, we again need to use the constructor function new Date().

const sortedDates = sortedArr.map(a => new Date(a));

The sortedDates is the actual date array.

b) In ascending order:

The ascending order works the same way as the descending order. But there is a minor but an important difference. Let’s demonstrate it with the code.

const sortedArr = dateArr.sort((a, b) => a.getTime() - b.getTime());

Try sorting a JavaScript date array on Codepen:

See the Pen Sort a date array in JavaScript by nadeem (@nasyxnadeem) on CodePen.

10) How to set timezone offset using JavaScript ?

Timezone offset in JavaScript is the difference between Local and UTC time in minutes. Timezone offset is calculated using the .getTimezoneOffset() method. The .getTimezone offset() method return minutes.

const date = new Date();
let difference = date.getTimezoneOffset();
console.log(difference);

Output:

-330

11) How to convert date to a JSON object?

To convert a JavaScript date object to a JSON object we use the .toJSON() method, for example

const date = new Date();
console.log(date.toJSON())

Output:

"2022-03-13T19:08:02.760Z"

12) Get date in locale from a JS date object?

To get the date in locale string we use the .toLocaleDateString() method. It only returns date and not the time, for example.

const date = new Date();
const text = date.toLocaleDateString();
console.log(text);

Output:

"3/14/2022"

13) Get time in locale from a JS date object?

To get the time in locale string we use the .toLocaleTimeString() method. It only returns time and not the date, for example.

const date = new Date();
const text = date.toLocaleTimeString();
console.log(text);

Output:

"12:44:07 AM"

Also read: 10 CSS pro tips, code this not that

14) Get date and time in locale from a JS date object?

To get both date and time in locale string we use the .toLocaleString() method. It returns both the date and the time, for example.

const date = new Date();
const text = date.toLocaleString();
console.log(text);

Output:

"3/14/2022, 12:45:36 AM"

Conclusion:

Although we didn’t cover everything about the date in JavaScript we made sure to cover the most important topics that you’d need in building JavaScript apps. We hope you got the most out of it. If you liked the content, please leave feedback in the comment section. And for more information please refer to JavaScript date Object Tutorial on W3School and JavaScript date reference on W3School or Date -MDN Web Docs.

Newsletter Updates

Enter your email address below to subscribe to our newsletter

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Programming & Tech Digest
Programming and Tech innovations delivered straight to your inbox for free.