CYBER MONDAY WEEK 🤑 Get 30% off your TNW for Startups or Scaleups packages when you use code CYBER30 only until December 4 →

This article was published on January 15, 2021

How to manipulate date and time in JavaScript


How to manipulate date and time in JavaScript Image by: Unsplash

In theory, handling dates as a developer is as simple as creating, storing, and, if necessary, manipulating dates. But as a JavaScript developer, you would know this theory doesn’t hold long after you start working with dates for real. On top of different date-time formats, you have to consider timezone and local differences.

For this reason, plenty of JavaScript developers seek help from third-party libraries when they have to manage dates in an application. While these libraries reduce the task’s complexity, having a clear understanding of handling vanilla JavaScript dates has its benefits.

This tutorial will introduce you to working with dates in vanilla JavaScript, as well as useful third-party libraries to help you simplify more complex date-related tasks.

JavaScript Date object

The Date object in JavaScript is the main element when it comes to handling date and time. It records a single point in time as the milliseconds’ number elapsed since the 1st January 1970 00:00:00 (UTC). This date-time combination is known as the epoch time. As far as JavaScript is concerned, it’s the beginning of time in the world.

Creating Dates

You can simply create a date using new Date() . You can pass parameters to the Date constructor to create a date of your choice. The given parameter can take different forms.

The 💜 of EU tech

The latest rumblings from the EU tech scene, a story from our wise ol' founder Boris, and some questionable AI art. It's free, every week, in your inbox. Sign up now!

Pass a date string

You can pass a date string of an accepted format when creating a new Date object.

const date = new Date (“2020-12-31”);

Now, if we print the created date, it shows this.

Thu Dec 31 2020 01:00:00 GMT+0100 (Central European Standard Time)

In addition to the date we passed, the date object has more values, including a time and a timezone. Since we didn’t give a specific value for these parameters when creating the object, JavaScript uses the local time and timezone of the code’s system.

If we want to pass the time or timezone with the parameter string, we can use a format like this.

YYYY-MM-DDTHH:mm:ss.sssZ

  • YYYY: year
  • MM: month (1 to 12)
  • DD: date (1 to 31)
  • HH: hour in 24-hour format (0 to 23)
  • mm: minutes (0 to 59)
  • ss: seconds (00 to 59)
  • sss: milliseconds (0 to 999)
  • T is used to separate the date and time in the string
  • If Z is present, the time is assumed to be in UTC. Otherwise, it assumes the local time.

However, if T and Z are not present, the string’s created date may give different results in different browsers. In that case, to always have the same timezone for the date, add +HH:mm or -HH:mm to the end.

You can get the same results using the Date.parse function instead of passing the date string to the Date constructor. Date.parse is indirectly being called inside the constructor whenever you pass a date string.

The format used in these strings is the ISO 8601 calendar extended format. You can refer to its details in the ECMAScript specification .

Pass date arguments

You can directly pass the date arguments to the Date constructor without using confusing date strings. The order and length of each year, month, etc., are exactly as in a date string.

When we inspect the created date’s outcome, we can notice one crucial difference in the final date.

What’s weird? When we created the date, we used 9 for the month, which we could assume to be September. However, when we print the result, the month is October instead. Why is that?

JavaScript uses a zero-based index to identify each month in a year. This means, for JavaScript, January is represented by 0 instead of 1. Similarly, October is represented by 9 instead of 10.

In this method of creating a date, we can’t pass an argument to indicate its time zone. So, it’s defaulted to the local time of the system. But we can use the Date.UTC function to convert the date to UTC before passing it to the Date constructor.

Pass a timestamp

Remember that I mentioned JavaScript stores the time elapsed since the epoch time in the Date object? We can pass this elapsed time value, called a timestamp, to indicate the date we are creating.

Create a Date object for the current date and time

If you want to create a Date object for the current date and time of the system, use the Date constructor without passing any argument.

You can also use the Date.now() function for the same task.

Formatting dates

JavaScript provides several built-in functions to format a date. However, these functions only convert the date to a format specific to each one.

Let’s see how each formatting function works.

Internationalization API

ECMAScript Internationalization API allows the formatting of a date into a specific locale using the Intl object.

You can pass an options object to the DateTimeFormat function to display time values and customize the output.

Custom date formats

If you want to format the date to any other format beyond what these functions provide, you’ll have to do so by accessing each part of the date separately and combining them.

JavaScript provides the following functions to retrieve the year, month, date, and day from a Date object.

Now, you can convert the date to a custom format using retrieved parts.

Updating dates

JavaScript provides several methods to edit an already created date.

Comparing dates

If you want to know whether a specific date comes before another, you can use greater than and less than operators directly for comparison.

This is because Dates in JavaScript are objects, so each date has a different instance of the class, and the == or === operator are comparing the memory address instead of the actual values of the dates.

JavaScript date manipulation libraries

We can find several JavaScript date and time manipulation libraries as open-source projects or otherwise. Some of them, designed for all kinds of date-time manipulations, and some have a specific set of use cases. In this section, I’ll only talk about popular multi-purpose libraries.

Moment.js used to be the king of date manipulation libraries among JavaScript developers. However, its developers recently announced that it’s focusing on maintaining the current codebase instead of adding new features. They recommend looking for an alternative solution for those who are working on new projects.

So, apart from Moment.js, what are the libraries we can use to make our life easier as developers?

Date-fns

Date-fns in an open-source library supporting date parsing and formatting, locales, and date arithmetic like addition and subtraction. It’s dubbed as Lodash for dates due to its versatility.

Luxon

Luxon is a date-time manipulation library created by one of the Moment.js developers to suit modern application requirements. Similar to Date-fns, Luxon offers data formatting and parsing functions. Also, it has native Intl support and is chainable.

Summary

This tutorial discussed how to work with date and time in JavaScript with and without external libraries. Working with dates is always painful in almost (if not all) programming languages. Fortunately for us, JS and its ecosystem of libraries does all the heavy work for us, allowing us to focus on building features.

This article was originally published on Live Code Stream by Juan Cruz Martinez (twitter: @bajcmartinez), founder and publisher of Live Code Stream, entrepreneur, developer, author, speaker, and doer of things.

Live Code Stream is also available as a free weekly newsletter. Sign up for updates on everything related to programming, AI, and computer science in general.

Get the TNW newsletter

Get the most important tech news in your inbox each week.

Also tagged with


Published
Back to top