TOC
Built-in objects:

Date

Working with dates is a very common task when using any programming language, and fortunately for us, JavaScript can help us with that, thanks to the built-in Date object. However, the name is a bit misleading, because it doesn't only handle dates, but also time, as we'll see in this article, where we dig a bit deeper into this useful object.

Date constructor

In its most simple form, when you create a new Date object, it will represent the date and time at the point where it was created, as you can see from this simple example:

let date = new Date();
alert(date);
// Output will look like this: 
// Thu Mar 23 2023 10:46:40 GMT+0100 (Central European Standard Time)

When we output the date, it will be a very detailed version of the current date and time, including the timezone. We can of course change that, but more on that later. Let's talk a bit more about the parameters we can pass to the Date object, as it will change the behavior quite a bit.

Creating a specific date

We can create a specific date (and time) using several of the available constructors. The most exact way of doing this is by specifying all the components manually, as we'll see in this example:

// Year, Month, Day
let date1 = new Date(2023, 11, 31);
// Sun Dec 31 2023 00:00:00
alert(date1);

// Year, Month, Day, Hours, Minutes
let date2 = new Date(2024, 0, 1, 22, 30);
// Mon Jan 01 2024 22:30:00
alert(date2);

Notice that when we pass in a month to the Date object, it's not the actual month but the index of the month, which is zero-index based, meaning that it ranges from 0 (January) to 11 (December).

Another approach is to pass in a string with the date and (optionally) time, like this:

let dateString1 = "2023-12-31";
let date1 = new Date(dateString1);
alert(date1);

let dateString2 = "2023-12-31 22:30:42";
let date2 = new Date(dateString2);
alert(date2);

However, be careful when doing this! The result may vary, depending on the JavaScript engine/implementation, unless you consistently use the ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ).

These are the most commonly used ways of instantiating a Date object. For a full list, please consult the documentation.

Date methods

Once you have an instance of the Date object, you get access to a heap of useful methods. Not all of them will be covered here, but let's discuss the most interesting ones. If you need the full list, please check out the documentation.

Date.get* methods: getDate(), getMonth() etc.

To extract specific parts of a date, you can use one or several of the get* methods. There's one for every component of the date, so just call the one(s) you need. Here's an example:

let date = new Date(2023, 11, 31);
alert(date.getDate()); // 31
alert(date.getMonth()); // 11
alert(date.getFullYear()); // 2023

Two important things to consider here: Again, the month returned is the index of the month, so it's zero-based (January is 0, December is 11), so you will have to add 1 if you need number of the month and not the index.

Also, you will notice that I call the method getFullYear(), but why does it suddenly require the word "full", when the other methods doesn't use that? Well, there is also a getYear() method, but it's deprecated and should NOT be used.

Date.get* methods: getHours(), getMinutes() etc.

You will also find methods for extracting the time components of the Date object - from hours and all the way down to milliseconds. Here's an example:

let date = new Date();
alert(date.getHours());
alert(date.getMinutes());
alert(date.getSeconds());
alert(date.getMilliseconds());

You may need these at some point, but if you're just looking to format a data and/or time in a specific way, there are methods better suited to do this. We'll get to them in a minute.

Date.get* methods: UTC variants

For all the get* methods we just talked about, there are also an https://en.wikipedia.org/wiki/Coordinated_Universal_Time variant. So, for instance, instead of calling getHours(), you may call getUTCHours() to obtain the hours in UTC. Let's see an example:

let date = new Date();
alert(date.getHours());
alert(date.getUTCHours());

Date.now()

This static method will return the number of milliseconds elapsed since the epoch (defined as midnight at the start of January 1, 1970, UTC). Example:

alert(Date.now());

Date.parse()

You may use the static parse() method found on the Date object to parse a string that holds a date (and optionally time). If the date string is successfully parsed, the result will be the amount of milliseconds since January 1, 1970, 00:00:00 UTC, which can then easily be turned into a Date object or be used for other types of calculations. Let's try an example:

let dateString = "July 20, 1969, 20:18:04 UTC";
let millisecondsSinceMoonLanding = Date.parse(dateString);
alert(millisecondsSinceMoonLanding);

let moonlandingDate = new Date(millisecondsSinceMoonLanding);
alert(moonlandingDate);

But as mentioned previously, be careful when doing this! The result may vary, depending on the JavaScript engine/implementation, unless you consistently use the ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ). So while other formats might seem to work in your favorite browser, it will likely not work across all engines and the behavior might even change in the future.

In case you supply an invalid date string, the parse() method will return NaN (Not a Number).

Date.set* methods: setDate(), setMonth() etc.

Just like the get* methods, which will return a specific component of the Date object, we have corresponding set methods, which will allow you to change the various parts of the Date object. For instance, we can quickly change the day of the month in a Date object, using the setDate() method, like this:

let date = new Date(2023, 11, 1);
// Example output: Fri Dec 01 2023 00:00:00
alert(date);

date.setDate(31);
// Example output: Sun Dec 31 2023 00:00:00
alert(date);

Now, in this example, we specify the value "31" as a parameter for the setDate() method because that's the date of the month we want. However, you may also specify a bigger number or even a negative number. Check out this example:

let date = new Date(2023, 11, 1);
// Example output: Fri Dec 01 2023 00:00:00
alert(date);

date.setDate(32);
// Example output: Mon Jan 01 2024 00:00:00
alert(date);

Notice how I have changed 31 to 32. Of course, there are only 31 days in the month of December, so JavaScript will carry over the leftover days and increment the other parts of the Date object accordingly. In this case, the new date will be the first day of January in the next year.

If we provide a negative number, the date will be updated by counting backwards from the last day of the previous month. So, for instance, -3 would result in the date being set to 3 days before the last day of the previous month:

let date = new Date(2023, 11, 1);
// Example output: Fri Dec 01 2023 00:00:00
alert(date);

date.setDate(-3);
// Example output: Mon Nov 27 2023 00:00:00
alert(date);

You can often use this to do some pretty creative date manipulations, and as mentioned, there are methods for all parts of the Date object. I won't go through all of them, as they mostly work similar to the setDate() method we just described in detail, but for all the specifics, please check out this reference. Here you will also find the setUTC* method variants.

Date.toString() / Date.toDateString() / Date.toTimeString()

Whenever you output a Date object, its toString() method is called, returning both date and time nicely formatted in the English format, using the local timezone. We have already seen this in action several times in the examples above, but for completeness, here's a short example of it:

let date = new Date();
alert(date);
// Example output: Thu Mar 30 2023 10:30:26 GMT+0200 (Central European Summer Time)

As mentioned, the toString() method is automatically called in the example above. However, if you only need the date or time component of the Date object, we can use the toDateString() and toTimeString() methods. They are actually used by the toString() method, which will simply return the result of these two methods separated by a space, as illustrated by this example:

let date = new Date();
// Example output: Thu Mar 30 2023 10:30:26 GMT+0200 (Central European Summer Time)
alert(date.toString());

// Example output: Thu Mar 30 2023
alert(date.toDateString());

// Example output: 10:30:26 GMT+0200 (Central European Summer Time)
alert(date.toTimeString());

And once again, if you're looking for UTC, there's also a toUTCString() method.

Date.toLocaleString() / Date.toLocaleDateString() / Date.toLocaleTimeString()

As mentioned, the regular toString() methods will use the English format when formatting the date. If this is not the behavior you're looking for, e.g. because you want dates to use a format that will match the language of your website/application, then you can use the toLocale* variants.

Without any parameters, these methods will format date and/or time according to the default locale. If you're running JavaScript in a browser, the default locale will usually be supplied by the browser, based on the user settings. You can test this by running the following example and see if the format is what you would expect:

let date = new Date();
// Example output: 3/30/2023, 10:49:31 AM
alert(date.toLocaleString());

// Example output: 3/30/2023
alert(date.toLocaleDateString());

// Example output: 10:49:31 AM
alert(date.toLocaleTimeString());

However, these methods also accepts two parameters: locale and options. The first parameter, locale, allows you to specify which locale should be used to format the date. You should use a IETF BCP 47 language tag to specify which locale should be used - here's a couple of examples:

let date = new Date();
// Example output (English, US): 3/30/2023, 11:12:26 AM
alert(date.toLocaleString("en-US"));

// Example output (Spanish, Spain): 30/3/2023, 11:12:26
alert(date.toLocaleString("es-ES"));

// Example output (German, Germany): 30.3.2023, 11:12:26
alert(date.toLocaleString("de-DE"));

And of course, you can also use the toLocaleDateString() and toLocaleTimeString() variants here, if you only need the date or time parts.

As the second parameter, referred to as options, you can completely customize the way the date is formatted. There are a LOT of options, so I won't go into details about them, but instead just show you an example:

let date = new Date();

let dateOptions = 
{	
	weekday: "long",  
	month: "long",
	year: "numeric",
	day: "numeric",
	hour: "numeric",
	minute: "numeric",
	hour12: false
};

// Example output: Thursday, March 30, 2023 at 23:31
alert(date.toLocaleString("en-US", dateOptions));

For the full list of options, please see this reference.

Summary

As you can see from the examples of this article, the Date object is quite useful when working with dates in JavaScript, supplying various methods for parsing and formatting.

However, if you come from another, modern programming language, like Java or C#, you may miss some date related features. If so, you may look into using one of the many JavaScript date libraries like Day.js or https://date-fns.org/. They will add a LOT of date related functionality that might come in handy for the more complex use cases.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!