DEV Community

Martin Capodici
Martin Capodici

Posted on

JavaScript Dates

If you do any amount of programming, you will likely cross the thorny subject of dates and times. It's a tricky subject because of all of the world's time zones, changing clocks, leap years and other oddities. That said, it is simple to get started with dates in JavaScript, and this tutorial will explain most of what you can do with Dates in Javascript, as well as touch on a library you can use if you need more.

What is a JavaScript Date?

A Date in JavaScript is an object that represents a date and time. JS Dates can go back or forward about 280,000 years and are accurate to the nearest millisecond (thousandth of a second). Inside the Date object there is just one value which is the number of milliseconds before or after 01 Jan 1970 in UTC time. UTC time is a standard time used to help coordinate time across the world. It is similar to the Greenwich Mean Time (GMT) time zone.

When dealing with JavaScript dates, you are really just dealing with a number, such as 819131040000. However dealing with numbers like that is inconvenient so there are helper functions in JavaScript to make dates, query them and manipulate them. We'll look at those soon, but first lets make a date.

Creating a JavaScript Date

Create a JS Date from today's date and the current time

Here is an example of creating a date that sets it to today's date and time:

var today = new Date();

You can now view what is in that date by using one of the methods on Date, such as toDateString:

console.log(today.toDateString()); 
// Returns a string like: "Fri Mar 01 2019"

console.log(today.toTimeString()); 
// Returns a string like: "05:00:00 GMT+1100 (Australian Eastern Daylight Time)"

The format used in the toDateString and toTimeString methods isn't specified in Javascript. This means different web browsers could return different formats, and it might depend on your computer's locations settings too.

Aghhh! - time zones

Judging from the second result, which contains "GMT+1100" and "Australian Eastern Daylight Time", time zones are a factor here, so let's discuss them quickly.

The today variable from the previous example is set to today's date and time, and this is stored in UTC time. The code was run in Australia and the UTC date and time, at that time, was 6pm on February 28th 2019 UTC. The today variable knows that it is '6pm on February 28th 2019 UTC'.

When toDateString and toTimeString are called they use the current time zone of the browser, and convert the internal date and time to that time zone. In this case it happens to be in Australia again, so the results are produced according to that, i.e. '5am on March 1st 2019 AEDT'.

We will see this UTC conversion process a few more times through the tutorial, so don't worry if it seems a bit confusing now.

What if you want to create a date with a specific date and time?

There are 3 ways to do this:

Create a JS Date by parts

If you need a specific date and time, rather than the current time, the recommend way to create a date is to specify the year, month, day, hours, minutes and seconds. This can be done as follows:

var date = new Date(2019, 02, 03, 00, 00, 00); // 03 March 2019 in local time zone.

The arguments are as follows:

  • Year
  • Month (zero based, so 0 = January, 1 = February etc.)
  • Days
  • Hours
  • Minutes
  • Seconds

The date and time is converted from local time to a UTC-based number inside the Date object. This means you can call methods on Date to find it's UTC value. You can use other methods to see what that the time is locally too.

To see this in action, look at this example, when run in Australia, using getDate and getUTCDate to pull out the day of the month from a Date we have just created:

new Date(2019, 2, 3, 00, 00, 00).getUTCDate(); // 2
new Date(2019, 2, 3, 00, 00, 00).getDate(); // 3 

Whenever you are sending dates to another system (e.g. a web server) it is often wise to send them as UTC, because the place where they end up might be in a different time zone, and using UTC makes it easier to coordinate because you only need one conversion to get to or to get from UTC.

Create a JS Date by String

This is not recommended as it is not standardized and different browsers (or other JavaScript environments such as Node, embedded devices, etc.) may give different results.

var date = new Date('2019-03-03T00:00:00');

This will also treat the time you give as a local time and convert it under the hood to UTC.

The only good time to use this is if you have an ISO formatted string. I'll tell you how to create one of those later in the tutorial.

Create a JS Date from a number

You can create a date from the "unix timestamp", which is the number of milliseconds since 01 Jan 1970. This number is how JavaScript Date stores the date internally anyway. It is a useful method if you are given such a timestamp from a server, which sometimes happens because some databases store dates that way.

var date = new Date(1551531600000);

Querying JavaScript Dates

Locally

There are a bunch of methods for getting the local date and time information from a date object. They are summarized here. All of them return the result for the local time zone:

Date

  • getFullYear() - Returns the year, with 4 digits if it is a 4 digit year.
  • getMonth() - Returns the month, with 0 being January, 1 is February etc.
  • getDate() - Returns the day of the month.
  • getDay() - Returns the day of the week, 0 being Monday, 1 being Tuesday etc.

Time

  • getHours() - Returns the hour.
  • getMinutes() - Returns the minutes.
  • getSeconds() - Returns the seconds.
  • getMilliseconds() - Returns the milliseconds.

Here is an example:

var date = new Date(2019, 2, 3, 0, 0, 5);
// Note that Date object stores the date and time as UTC internally, but it is converted
// back to local time when these methods are used:
date.getFullYear(); // 2019
date.getMonth(); // 2, i.e. March
date.getSeconds(); // 5

In UTC

You can also get the UTC date and time information, with these equivalent methods:

  • getUTCFullYear()
  • getUTCMonth()
  • getUTCDate()
  • getUTCDay()
  • getUTCHours()
  • getUTCMinutes()
  • getUTCSeconds()
  • getUTCMilliseconds()

Here is an example that, using toUTCString as well to show you the full date that is stored inside.

var date = new Date(1551531600000);
date.toUTCString(); // Returns "Sat, 02 Mar 2019 13:00:00 GMT"
date.getUTCDate(); // 2
date.getDate(); // 1,2 or 3 depending on your local time zone.

Changing JavaScript Dates

All of the get methods above also have a set equivalent, so that you can change a date:

  • setFullYear()
  • setMonth()
  • setDate()
  • setDay()
  • setHours()
  • setMinutes()
  • setSeconds()
  • setMilliseconds()
  • setUTCFullYear()
  • setUTCMonth()
  • setUTCDate()
  • setUTCDay()
  • setUTCHours()
  • setUTCMinutes()
  • setUTCSeconds()
  • setUTCMilliseconds()

Each of these methods takes in a number in the same format as returned by the equivalent get......() method. Here are some examples:

var date = new Date(2019, 2, 3, 0, 0, 5);
date.getFullYear(); // 2019
date.setFullYear(2020);
date.getFullYear(); // 2020

var date = new Date(1551531600000);
date.toUTCString(); // Returns "Sat, 02 Mar 2019 13:00:00 GMT"
date.setUTCHours(10); 
date.toUTCString(); // Returns "Sat, 02 Mar 2019 10:00:00 GMT"

Conversion

There are some methods for converting the date to different formats. Here are the most useful ones:

Date Method Time Zone Returns
toDateString() Local Date portion of the date, in a format to be read by a human. The format might vary from browser to browser.
toTimeString() Local Time portion of the date, in a format to be read by a human. The format might vary from browser to browser.
toUTCString() UTC Date and time portion of the date, in a format to be read by a human. The format might vary from browser to browser.
toISOString() UTC Date and time as UTC time in YYYY-MM-DDTHH:mm:ss.sssZ format ( ISO 8601 Extended Format).
toLocaleDateString() Local Date portion of the date, e.g. "3/2/2019", formatted based you on your computers's locale settings. The order of the month and day will depend on those settings, for example.
toLocaleTimeString() Local Time portion of the date, e.g. "9:00:00 PM", formatted based you on your computers's locale settings. The type of clock 12 hour or 24 hour will depend on those settings, for example.

There are some similar methods that are less useful, or are not a fully accepted standard so may not work in your browser. To see them click here

Examples, with results from my time zone. Your results might be different depending on your time zone, browser and computer's locale settings.

var date = new Date(2019, 2, 3, 0, 0, 5);
date.toDateString(); // "Sun Mar 03 2019"
date.toTimeString(); // "00:00:05 GMT+1100 (Australian Eastern Daylight Time)"
date.toUTCString(); // "Sat, 02 Mar 2019 13:00:05 GMT"
date.toISOString(); // "2019-03-02T13:00:05.000Z"
date.toLocaleDateString(); // "3/3/2019"
date.toLocaleTimeString(); // "12:00:05 AM"

None of those results above are guaranteed to be the same on your computer because when we create the date, the date is converted from the local time zone to UTC. So your date might be different to mine in the first place. And even then, most of those methods return formats that are dependent on your computer settings.

Be careful ...

...with methods that depend on time zone and computer settings

Most of the methods I just listed depend on time zone, your browser and your computer settings. They should be used with care. They are fine for showing a date to the user, but they are not recommended if that same date is going to be read again by your program (or someone else's). This is because you can't predict the format the string will be in. The day of month and month might be in a different order to what you expect, then the code using that date will get it wrong sometimes.

I recommend:

  • If you need to pass dates around your program, keep them as Date objects if possible.
  • When sending dates to a server or service, use the toISOString to format the date because it is a standard format and uses UTC. Alternatively use the getTime to get the number of milliseconds since 01/01/1970, and this is also in UTC.
  • When receiving dates from a server or service, if you have any control or influence, try to make sure they are sent as an ISO string or milliseconds since 01/01/1970, and then you can pass them as the argument to new Date().
  • Only use the toDateString, toTimeString, toUTCString, etc. methods for strings that will be shown to a user of your web page.
  • Be careful when using libraries with calendar controls, and read the documentation about what date format's they expect to work with.

Moment.js

Do you need to do something with dates that the Javascript Date object cannot support? For example formatting dates using a format string? Or more advanced time zone conversions?

Moment.js is a library that gives you more power to work with Dates in JS, and is recommended if you are struggling to achieve what you need with the standard JavaScript Date object. I will write a separate tutorial for moment.js in the future.

The first example from the moment.js website shows you that you can format dates to your liking with this library:

moment().format('MMMM Do YYYY, h:mm:ss a'); // March 2nd 2019, 9:06:12 am
moment().format('dddd');                    // Saturday
moment().format("MMM Do YY");               // Mar 2nd 19
moment().format('YYYY [escaped] YYYY');     // 2019 escaped 2019
moment().format();                          // 2019-03-02T09:06:12+11:00

Footnote on UTC

Early I said that UTC is similar to Greenwich Mean Time (the UK's winter time zone). However it is not the same! There can be up to 1 second difference between the two.

This is because there aren't exactly 24 hours in a day. Our planet is a big lump of rock, not a Rolex. And it's slowing down. GMT tracks the rotation of the earth to keep the kind of time we are used to. UTC uses scientifically accurate seconds, but needs adjustments along the way to keep it in sync with the Earth's rotation.

Did I say before dates and times are tricky? In any case, for almost all cases you won't have to worry about that 1 second but it is useful to know, and it shows that we must treat dates and times with a lot of care.

Summary

This tutorial covered the Date object in Javascript, and it is pretty good at giving you basic functionality to deal with dates. Sometimes this will be too limited for you and you will need to use a library like moment.js, or at least some 'utility functions' that you keep in a certain part of your program. It is good to be aware of time zones, and that a JavaScript Date is a UTC based date under the hood, even if you create it and query it in the local time zone.

This article was originally posted at Super JavaScript: JavaScript Dates

Top comments (3)

Collapse
 
mcapodici profile image
Martin Capodici

Been a while since I looked at this. These days I use date-fns.org/ instead of Moment. The interface seems a little cleaner.

Collapse
 
guilhermemiua profile image
Guilherme Eiti Akita Miua

Wow! I learned a lot by reading this articule. Thank you very much!

Collapse
 
aiosifelis profile image
Andreas Iosifelis

Very good article. It clarified a lot of things for me. Thank you!