Convert a dd/mm/yyyy string to a Date in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Convert a dd/mm/yyyy string to a Date in JavaScript #

To convert a dd/mm/yyyy string to a date:

  1. Split the string on each forward slash to get the day, month and year.
  2. Pass the year, month minus 1 and the day to the Date() constructor.
  3. The Date() constructor creates and returns a new Date object.
index.js
const str = '22/04/2022'; const [day, month, year] = str.split('/'); console.log(day); // 👉️ 22 console.log(month); // 👉️ 04 console.log(year); // 👉️ 2022 const date = new Date(+year, month - 1, +day); console.log(date); // 👉️ Fri Apr 22 2022

We used the split method to split the string on each forward slash /.

The method returns an array containing the substrings.

index.js
const str = '22/04/2022'; // 👇️ ['22', '04', '2022'] console.log(str.split('/'));

We used array destructuring to assign the values to variables in a single statement.

The Date() constructor takes the year, month (0 = January to 11 = December), day of the month, hours, minutes and seconds as parameters and returns a Date object.

We used the unary plus (+) operator to convert the strings to numbers when passing them to the Date() constructor.

Notice that we subtracted 1 from the month when passing it to the Date() constructor.

This is because, the Date constructor expects a zero-based value, where January = 0, February = 1, March = 2, etc.

Here is an example that converts a date and time string formatted as dd/mm/yyyy hh:mm:ss to a Date object.

index.js
const str = '22/04/2022 07:30:16'; const [dateComponents, timeComponents] = str.split(' '); console.log(dateComponents); // 👉️ "22/04/2022" console.log(timeComponents); // 👉️ "07:30:16" const [day, month, year] = dateComponents.split('/'); const [hours, minutes, seconds] = timeComponents.split(':'); const date = new Date(+year, month - 1, +day, +hours, +minutes, +seconds); console.log(date); // 👉️ Fri Apr 22 2022 07:30:16

The first thing we did was split the date and time string on the space, so we can get the date and time components as separate strings.

We then had to split the date string on each forward slash to get the value for the day, month and year. The approach is the same even if the separator is different, e.g. a hyphen.

We also split the time string on each colon and assigned the hours, minutes and seconds to variables.

Notice that we subtracted 1 from the month when passing it to the Date() constructor.

This is because, the Date constructor expects a zero-based value for the month, where January = 0, February = 1, March = 2, etc.

We then passed all of the parameters to the Date() constructor to create a Date object.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.