Javascript

Javascript Dates and How they Work

Sponsor

Javascript dates are notorious for being difficult to handle. In this tutorial, we'll be looking at how Javascript dates work, and how you can manipulate them to your liking.

Creating dates

To create dates, we typically use the Date() function. To get the current date, for example, we can do the following:

javascript Copy
let date = new Date(): // Console logs the current date. console.log(date); // i.e. Fri Jul 09 2021 20:22:04 GMT+0100 (British Summer Time)

Everything then is based around using new Date(). Let's look at some typical use cases and how they work with this new Date() function.

Getting the current timestamp

A unix timestamp is the number of seconds since Jan 1st, 1970. To get the unix timestamp in Javascript, we use the function getTime(). Strangely, Javascript gives the time stamp in milliseconds - if you want it in seconds you will have to divide the final number by 1000.

javascript Copy
let date = new Date().getTime(): // Console logs the current time stamp. console.log(date); // i.e. 1625858618210

As you might have guessed, there are a number of functions which can run off the date function in this way. Let's take a look at some more.

Getting the day, month or year

The following functions cover day, month and year retrieval:

  • new Date().getDay() - gets the day of the week counting from 0 and starting on Sunday, so Friday would be 5.
  • new Date().getDate() - gets the date of the month, so the 9th July would return 9.
  • new Date().getMonth() - gets the number of the current month counting from 0, so the 9th July would return 6.
  • new Date().getFullYear() - gets the number of the current year, i.e. 2021.
  • new Date().getSeconds() - gets the current seconds count.
  • new Date().getMilliseconds() - gets the milliseconds count (from 0 - 999).
  • new Date().getMinutes() - gets the current minutes count.
  • new Date().getHours() - gets the current hours count.
  • new Date().getTimezoneOffset() - gets the timezone offset from 0, counted in minutes.

Javascript often gives us dates in limited formats, so using the functions above, an example is shown to get the current time and date, and put it into a custom format:

javascript Copy
let date = new Date(); let day = date.getDate(); let month = date.getMonth(); let year = date.getFullYear(); let hours = date.getHours(); let minutes = date.getMinutes(); let myCustomDateFormat = `${day}-${month}-${year} at ${hours}:${minutes}`;

These functions all give us some flexibility in gathering the current date and time, but what if we want to change the time of an already existing date? Let's look at how that works:

As with getting the date, month, or year, we also have related functions which set the date and time. You can figure these functions out by replacing the word get with set from the functions above.

For example, getDay() becomes setDay(). Let's look at an example where we update the year and hour of a date:

javascript Copy
let date = new Date(); console.log(date); // Returns Fri Jul 09 2021 20:37:51 GMT+0100 (British Summer Time) // Now let's update the date date.setFullYear(2016); date.setHours(12); console.log(date); // Returns Fri Jul 09 2016 12:37:51 GMT+0100 (British Summer Time)

Converting to standard date strings

One of the most widely used date formats is the ISO 8061 format. This format looks like 2021-07-09T20:38:49.452Z. To convert a date to that, we simply use toISOString().

javascript Copy
let date = new Date(); let utcDate = date.toISOString(); // Console logs something like 2021-07-09T20:38:49.452Z console.log(utcDate);

Localised formats

As you may know, different countries have different date formats, so Javascript wanted to support them as well. For that, we have three functions:

  • new Date().toLocaleString - allows us to set the format showing both time and date.
  • new Date().toLocaleDateString - allows us to set the format showing date only.
  • new Date().toLocaleTimeString - allows us to set the format showing time only.

This format has two optional parameters. One is the format we wish to use, which is a code like en-US. You can find the full list here. The second is an object which defines if the different parts of the date should be numerical or long (in text format).

An example is given below, using toLocaleString:

javascript Copy
let date = new Date(); let localOptions = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', 'minute' : 'numeric' }; let inFrench = date.toLocaleString('fr-FR', localOptions); // Returns vendredi 9 juillet 2021, 21:53 console.log(inFrench);

Parsing dates

Parsing dates from strings can be particularly hard in Javascript. The easiest way is to manually split your date using functions like String.split(), and then passing this into the new Date() function. You can pass a string date straight into the date function, but browser differences makes it quite unreliable.

Let's first look at an example where we split the date and time:

javascript Copy
let stringDate = '950/02/01'; // Let's split our date.. // This will give us [ '950', '02', '01' ] as an array let splitDate = stringDate.split('/'); // And then force each of those splits to a number let year = parseFloat(splitDate[0]); // We subtract 1 from month, since it starts counting from 0. let month = parseFloat(splitDate[1]) - 1; let day = parseFloat(splitDate[2]); // Date has the following format. We don't have to give all the fields, and if we don't // it assumes 0 for time, and 1 for dates. // new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds) // That means we can do ... let newDate = new Date(year, month, day); // This will return something like Sun Mar 01 0950 00:00:00 GMT-0001 (Greenwich Mean Time) console.log(newDate);

Dates aren't always that simple though, but we can pretty much achieve most date parses by splitting into an array. A more complicated split may look like this:

javascript Copy
let timeDate = '01/01/2021 22:34'; // Start by splitting by space, giving us [ '01/01/2021', '22:34' ] let startSplit = timeDate.split(' '); // Then split again, for date, giving us [ '01', '01', '2021' ]; let dateSplit = startSplit[0].split('/'); // Then split for time, giving us [ '22', '34' ]; let timeSplit = startSplit[1].split(':'); // Then parse it all for date... let day = parseFloat(dateSplit[0]); let month = parseFloat(dateSplit[1]); let year = parseFloat(dateSplit[2]); // And for time... let hour = parseFloat(timeSplit[0]); let minute = parseFloat(timeSplit[1]); // Gives us '1-1-2021 22 34' console.log(`${day}-${month}-${year} ${hour} ${minute}`);

If a string is in a known format, it may be formattable by the Date() function itself. As mentioned, this is not recommended, but it will work in most browsers for standard strings such as time ISO strings:

javascript Copy
let parseDate = new Date('0950-02-01T00:01:15.000Z').getTime(); // returns -32185382325000 console.log(parseDate);

Parse function

Javascript also has a parse functions, which you can access via new Date().parse(). However, this does exactly the same thing as passing your date string directly into new Date(), as we did above.

Conclusion

You may have noticed in this article that there are a lot of inconsistencies with how dates are implemented in Javascript. Some functions start counting at 0, and some do not. Some functions seem like duplicates, while parsing existing dates seems very difficult to achieve.

Fortunately, in the future we will be able to use the emerging Temporal functions, which is much easier. We won't cover those today, but links to that and other useful resources can be found below:

Last Updated Friday, 9 July 2021

Subscribe to Newsletter

Subscribe to stay up to date with our latest web development and software engineering posts via email. You can opt out at any time.

Not a valid email