Date
Working with dates is something that happens quite frequently in applications.
JavaScript offers us a date handling functionality through a powerful built-in object: Date
.
A Date object instance represents a single point in time.
Despite being named Date
, it also handles time.
Initialize the Date object
We initialize a Date object by using
This creates a Date object pointing to the current moment in time.
Internally, dates are expressed in milliseconds since Jan 1st 1970 (UTC). This date is important because as far as computers are concerned, thatās where it all began.
You might be familiar with the UNIX timestamp: that represents the number of seconds that passed since that famous date.
Important: the UNIX timestamp reasons in seconds. JavaScript dates reason in milliseconds.
If we have a UNIX timestamp, we can instantiate a JavaScript Date object by using
If we pass 0 weād get a Date object that represents the time at Jan 1st 1970 (UTC):
If we pass a string rather than a number, then the Date object uses the parse
method to determine which date you are passing. Examples:
Thereās lots of flexibility here. You can add, or omit, the leading zero in months or days.
Be careful with the month/day position, or you might end up with the month being misinterpreted as the day.
You can also use Date.parse
:
Date.parse
will return a timestamp (in milliseconds) rather than a Date object.
You can also pass a set of ordered values that represent each part of a date: the year, the month (starting from 0), the day, the hour, the minutes, seconds and milliseconds:
The minimum should be 3 parameters, but most JavaScript engines also interpret less than these:
In any of these cases, the resulting date is relative to the timezone of your computer. This means that two different computers might output a different value for the same date object.
JavaScript, without any information about the timezone, will consider the date as UTC, and will automatically perform a conversion to the current computer timezone.
So, summarizing, you can create a new Date object in 4 ways
passing no parameters, creates a Date object that represents ānowā
passing a number, which represents the milliseconds from 1 Jan 1970 00:00 GMT
passing a string, which represents a date
passing a set of parameters, which represent the different parts of a date
Timezones
When initializing a date you can pass a timezone, so the date is not assumed UTC and then converted to your local timezone.
You can specify a timezone by adding it in +HOURS format, or by adding the timezone name wrapped in parentheses:
If you specify a wrong timezone name in the parentheses, JavaScript will default to UTC without complaining.
If you specify a wrong numeric format, JavaScript will complain with an āInvalid Dateā error.
Date static methods
You can invoke 3 methods on the Date object:
Date.now()
Date.now()
Returns the current timestamp in millieseconds.
Usage:
See the section below titled āGet the current timestampā for more details on getting the timestamp.
Date.parse()
Date.parse()
Parses a string representation of a date and return the timestamp.
Usage:
Date.UTC()
Date.UTC()
Remember the Date constructor from above? We cna pass it 3 or more parameters to indicate the year, the month (starting from 0), the day, the hour, the minutes, seconds and milliseconds:
Date.UTC()
works in the same way, but returns a timestamp rather than a Date object:
Date conversions and formatting
Given a Date object, there are lots of methods that will generate a string from that date:
The Date object getter methods
A Date object offers several methods to check its value. These all depends on the current timezone of the computer:
There are equivalent UTC versions of these methods, that return the UTC value rather than the values adapted to your current timezone:
Editing a date
A Date object offers several methods to edit a date value:
setDay and setMonth start numbering from 0, so for example, March is month 2.
Fun fact: those methods āoverlapā, so if you, for example, set date.setHours(48)
, it will increment the day as well.
Good to know: you can add more than one parameter to setHours()
to also set minutes, seconds and milliseconds: setHours(0, 0, 0, 0)
- the same applies to setMinutes
and setSeconds
.
As for get*, also set* methods have an UTC equivalent:
Get the current timestamp
The UNIX timestamp is an integer that represents the number of seconds elapsed since January 1 1970.
On UNIX-like machines, which include Linux and macOS, you can type date +%s
in the terminal and get the UNIX timestamp back:
The current timestamp can be fetched by calling the now()
method on the Date
object:
You could get the same value by calling
Note: IE8 and below do not have the now() method on Date. Look for a polyfill if you need to support IE8 and below, or use new Date().getTime() if Date.now is undefined (as thatās what a polyfill would do)
The timestamp in JavaScript is expressed in milliseconds.
To get the timestamp expressed in seconds, convert it using:
Note: some tutorials use Math.round(), but that will approximate the the next second even if the second is not fully completed.
Iāve seen tutorials using
which might seem a weird statement, but itās perfectly correct JavaScript code. The unary operator + automatically calls the valueOf()
method on any object it is assigned to, which returns the timestamp (in milliseconds). The problem with this code is that you instantiate a new Date object thatās immediately discarded.
Pay attention. If you overflow a month with the days count, there will be no error, and the date will go to the next month:
The same goes for months, hours, minutes, seconds and milliseconds.
Format dates according to the locale
The Internationalization API, well supported in modern browsers (notable exception: UC Browser), allows you to translate dates.
Itās exposed by the Intl
object, which also helps localizing numbers, strings and currencies.
Weāre interested in Intl.DateTimeFormat()
.
Hereās how to use it.
Format a date according to the computer default locale:
Format a date according to a different locale:
Intl.DateTimeFormat
method takes an optional parameter that lets you customize the output. To also display hours, minutes and seconds:
Hereās a reference of all the properties you can use.
Compare two dates
You can calculate the difference between two dates using Date.getTime()
:
In the same way you can check if two dates are equal:
Keep in mind that getTime() returns the number of milliseconds, so you need to factor in time in the comparison. July 10, 2018 07:22:13
is not equal to new July 10, 2018
. In this case you can use setHours(0, 0, 0, 0)
to reset the time.
How to determine if a date is today in JavaScript
How can you determine if a JavaScript Date object instance is a representation of a date/time that is ātodayā?
Given a Date instance, we can use the getDate()
, getMonth()
and getFullYear()
methods, which return the day, month and year of a date, and compare them to today, which can be retrieved using new Date()
.
Hereās a small function that does exactly that, returning true if the argument is today.
You can use it like this:
Last updated
Was this helpful?