How to use the native date object in JavaScript

In this tutorial, we are going to learn how to use the native date object in JavaScript. Before we get into the tutorial, in most cases, we’re using some sort of external libraries such as momentjs to handle all of our date and time and other operations. But in some cases, we might find this native date object is more than enough to suit our own needs.

So an instance of a date or a date object represents a point in time. It lets us do basic operations with date and time. So it will be much easier to demonstrate using code as usual.

CONTENTS

How to create a date object in JavaScript?

We are going to look at the four main ways that we can make date objects. So the first one looks like below.

Date object with no arguments provided:

let d;
d = new Date();

console.log(d.toString());

So in the above example, we have initialized a new Date instance into a variable called d. By this method, we are calling the constructor of the Date object. So this just means that the variable d is now a date object.

By calling the constructor with no arguments provided, it’ll make a new date instance or object for the current date and time. So when the page loads up, the variable d will be going to represent a date object for the current date-time. Let’s refresh the page and check the console window.

"Sun Jun 20 2021 21:39:36 GMT+0530 (India Standard Time)"

Here we get Sunday, Jun 20, and also shows my timezone information (at the time when I was writing this article). So that is the most basic way to create a date object.

Date object with milliseconds as argument :

So let’s take a look at the second way to create an instance. This will be done by using the number of milliseconds as an argument.

let d;
d = new Date(523980360000);

console.log(d.toString());

Output:

"Sat Aug 09 1986 19:36:00 GMT+0530 (India Standard Time)"

Here we passed 523980360000 as UNIX timestamp as an argument. Now we get August 9th, 1986 with the time zone. It is created a new date instance to represent the point in time.

Date object with date time string as argument :

The third way we are going to create a Date object is bypassing a date-time string. A quick disclaimer according to the Mozilla Developer Network or the mdn documentation this method is not recommended and always strongly discouraged.

The reason is that there are differences in the browser which is running the JavaScript. Some browsers might interpret things differently. But if we provide an ISO 8601 date-time string to the date constructor, it will be going to work fine and consistently across the different browsers.

For example, we are going to pass an ISO 8601 formatted date-time string as an argument. So this might look something like this-

let d;
d = new Date("2021-06-20T10:30:00+05:30");

console.log(d.toString());

Here we passed 2021 as year and the 6th month so June 20th. After that, we have used “T” to separate the date part from the time part. The time part we have passed 11:30 in the morning or a.m. and this +05:30 is my UTC or my GMT offset. If we load page, we will get the below output.

"Sun Jun 20 2021 10:30:00 GMT+0530 (India Standard Time)"

So using this method by passing an ISO 8601 string which most of the databases or most server-side frameworks or languages should be able to understand.

Date object passing individual parts as argument :

So in the last method, we will go to pass the individual parts of the date that make up the data itself. So let’s check the syntax first.

Date( year, index of month, <em>day, hour, min, sec, ms</em>);

So let’s pass the argument of the date part to the Date() object.

let d;
d = new Date(2021, 5, 20, 10, 30, 12, 0 );

console.log(d.toString());

Output:

"Sun Jun 20 2021 10:30:12 GMT+0530 (India Standard Time)"

In the above example, check the 2nd argument which is an index of a month. So the month index starts from 0 and ends with 11. For example, 11 would be December, and 0 would be January. Here we used 5 so it displayed the month of June.

We can also not specify anything after the month. So all we need to do is provide the year and the month.

let d;
d = new Date(2021, 5);

console.log(d.toString());

Output:

"Tue Jun 01 2021 00:00:00 GMT+0530 (India Standard Time)"

If we refresh the page, we can see here it is chosen the first day of the month of June the hour minute and second will be zero. So it’s gonna default to the first value of each part if we don’t actually provide it.

JavaScript date object getter methods:

We have already constructed a date object so now let’s use them and cover things like the getters method.

  1. getFullYear() – This method will show the four digits year of the date instance.
  2. getYear() – This method will return the year in two or three digits format.
  3. getMonth() – This will return month index. The month index starts from 0. So December is 11 and January is 0.
  4. getDate() – It will return the date (1 to 31) of that month from the date instance.
  5. getDay() – It will return the day in a week where 6 is for Saturday and 0 is for Sunday.
  6. getTime() – It will show the time in milliseconds starting from 1st January 1970.
  7. getHours() – This method will return the hours in 24 hours from starting from 0 to 23.
  8. getMinutes() – It will return minutes.
  9. getSeconds() – It will return seconds.
  10. getMilliseconds() – It will return milliseconds.
  11. getTimezoneOffset() – Return the time zone offset from the date instance.

Let’s check an example of the above methods from the current date instance.

let d;
d = new Date();

console.log("Given date : " + d.toString());
console.log("getFullYear() : " + d.getFullYear());
console.log("getYear() : " + d.getYear());
console.log("getMonth() : " + d.getMonth());
console.log("getDate() : " + d.getDate());
console.log("getDay() : " + d.getDay());
console.log("getTime() : " + d.getTime());
console.log("getHours() : " + d.getHours());
console.log("getMinutes() : " + d.getMinutes());
console.log("getSeconds() : " + d.getSeconds());
console.log("getMilliseconds() : " + d.getMilliseconds());
console.log("getTimezoneOffset() : " + d.getTimezoneOffset());

Output:

"Given date : Mon Jun 21 2021 11:34:42 GMT+0530 (India Standard Time)"
"getFullYear() : 2021"
"getYear() : 121"
"getMonth() : 5"
"getDate() : 21"
"getDay() : 1"
"getTime() : 1624255482154"
"getHours() : 11"
"getMinutes() : 34"
"getSeconds() : 42"
"getMilliseconds() : 154"
"getTimezoneOffset() : -330"

UTC Methods of getters:

To actually get the UTC version of each one of these parts it’s quite straightforward. So let’s take an example of that.

let d;
let d;
d = new Date();

console.log("Given date : " + d.toString());
console.log("getUTCFullYear() : " + d.getUTCFullYear());
console.log("getUTCMonth() : " + d.getUTCMonth());
console.log("getUTCDate() : " + d.getUTCDate());
console.log("getUTCDay() : " + d.getUTCDay());
console.log("getUTCHours() : " + d.getUTCHours());
console.log("getUTCMinutes() : " + d.getUTCMinutes());
console.log("getUTCSeconds() : " + d.getUTCSeconds());
console.log("getUTCMilliseconds() : " + d.getUTCMilliseconds());

Output:

"Given date : Mon Jun 21 2021 11:50:22 GMT+0530 (India Standard Time)"
"getUTCFullYear() : 2021"
"getUTCMonth() : 5"
"getUTCDate() : 21"
"getUTCDay() : 1"
"getUTCHours() : 6"
"getUTCMinutes() : 20"
"getUTCSeconds() : 22"
"getUTCMilliseconds() : 558"

JavaScript date object setters methods:

So we now have covered the getters. We can now move on to the setters. So these work in a very similar fashion. So let’s check a basic example of setters methods.

let d;
d = new Date(2021, 5, 20, 10, 30, 12, 0);

console.log(d.toString());

d.setFullYear(2022);
d.setDate(21);
d.setHours(11);

console.log(d.toString()); 

Output:

"Sun Jun 20 2021 10:30:12 GMT+0530 (India Standard Time)"
"Tue Jun 21 2022 11:30:12 GMT+0530 (India Standard Time)"

So here you can see, we have passed the part of the date as an argument to date object. After that, we have converted date object to a string. So it’s June 20, 2021, and the time is 10 hours morning.

But by using setters methods like setFullYear(), setDate(), or setHours() we can change the year, date, time, and other parts of a date instance.

In the above example, we have changed the year, date, and hours. So the year has been changed from 2020 to 2021 and also the is 21 and time is 11 am morning.

We can also UTC setters methods for example setUTCHours(5). It will change the UTC time of a date instance.

How to format Date object in different ways?

So the last thing we are going to cover here is how to display or format date objects in various ways.

ISO 8601 formatted date time:

This is really straightforward to print an ISO 8601 formatted date-time string by using toISOString() method.

let d;
d = new Date();

console.log(d.toISOString()); 

Output:

"2021-06-21T07:23:33.953Z"

We can see here this is the UTC version of the day object and obviously, it is for 07:00 a.m. like we see earlier and this is Z here represents UTC.

Okay, so that is definitely very useful when it comes to doing things like making a call to an external API or doing things like that where we want to the standard of point in time.

Locale string method date and time:

So this one’s a bit interesting and is quite useful. Let’s check an example first.

let d;
d = new Date();

console.log(d.toLocaleString("en-IN")); 
console.log(d.toLocaleString("en-US")); 

console.log(d.toLocaleDateString("en-IN")); 
console.log(d.toLocaleDateString("en-US")); 


console.log(d.toLocaleTimeString("en-IN")); 
console.log(d.toLocaleTimeString("en-US")); 

Output:

"21/6/2021, 2:04:04 pm"
"6/21/2021, 2:04:04 PM"

"21/6/2021"
"6/21/2021"

"2:04:04 pm"
"2:04:04 PM"

In the above example, we have passed a language tag. So for example, here we have passed the Indian language tag (“en-IN”) and also the United States language tag (“en-US”). Here we can see, this will show the date instance according to the Indian locale then according to the US locale.

JavaScript date object in JSON:

The next thing we are going to be cover that, what happens when we actually stringify using JSON. So let’s take an example of what the JSON stringify method does?

let d;
d = new Date();

console.log(JSON.stringify({
	published_date : d
}));

Output:

{'published_date':'2021-06-21T09:03:18.654Z'}

Here we have passed an object with a property called published_date and the date value is going to be simply a new instance of a date object called d.

We can see, it gives us the date-time string in that ISO 8601 format. So we’re getting the return value to serialize the date instance.

JavaScript date object to mm/dd/yyyy format:

Sometimes, we need to show convert date object to different formats i.e. mm/dd/yyyy format, dd/mm/yyyy or yyyy/mm/dd format. Basically, it will be very if we use any kind of date formatting library. But if we want it by using the native JavaScript method, we can easily do this. So let’s take an example that will convert the date object to mm/dd/yyyy format.

let d;
d = new Date();

function formatDate(date) {
    let year = date.getFullYear();
    let month = (1 + date.getMonth()).toString().padStart(2, '0');
    let day = date.getDate().toString().padStart(2, '0');
  
    return month + '/' + day + '/' + year;
}

console.log(formatDate(d));

Output:

06/21/2021

In the above example, we have added one to getMonth() returned value. As its index starts from 0. In our case the month is June. The above method will return 5 as it starts from 0. The padStart is used to make it double digits.

About Ashis Biswas

A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.

Leave a Comment