javascript

Convert a string to a date in JavaScript

The date is a unique data type in javascript. It can give us so much information using so little space.

When we interact with an API, we often receive the date as a string. Then if we need to parse that string to a date input, we convert the string to a date in javaScript, because most of the inputs do not support a raw string as an input.

A string date can be of three types and, we will convert each of those to a date object in javascript.

Formats of string date:

  • mm-dd-yyyy
  • yyyy-mm-dd
  • dd-mm-yyyy

To convert a string to date, we are going to use the new Date() constructor. The parameter can be a date string or timestamp or number of milliseconds. In our example, we are going to use string as an input.

Convert mm-dd-yyyy format string to date

The mm-dd-yyyy format is the default date format in javascript. Hence, we can pass the string directly in the new Date() constructor as below example.

let date_string = "04/03/2020"; // Apr 03 2020
let output = new Date(date_string);

console.log(output.toString()); // Fri Apr 03 2020 00:00:00

Convert dd-mm-yyyy format string to date

The new Date() constructor does not support this format is not supported as a direct input. So if you want to convert a dd-mm-yyyy format string to date then, there must be some pre-processing like below example.

 let date_string = "03/04/2020"; // Apr 03 2020
 let parts_of_date = date_string.split("/");

 let output = new Date(+parts_of_date[2], parts_of_date[1] - 1, +parts_of_date[0]);

 console.log(output.toString()); // Fri Apr 03 2020 00:00:00 

Notice in line number 3 we are using +parts_of_date[2] and +parts_of_date[0]. That is to convert a string to integer and pass in the constructor.

For the second parameter, we are subtracting 1. Because in javascript, the month starts from 0 and ranges between 0 to 11.

Convert yyyy-mm-dd format string to date:

We can pass the yyyy-mm-dd format string directly in the new Date() constructor as below example.

 let date_string = "2020/04/03/"; // Apr 03 2020
 let output = new Date(date_string);

 console.log(output.toString()); // Fri Apr 03 2020 00:00:00 

Easy, right? Remember these small steps, specifically the dd-mm-yyyy format to date. Many times we may get wrong date conversion issue after converting the date where it may be one day less than the actual input.

These type of issues can be solved by the same approach as described in the Convert dd-mm-yyyy format string to date section.

Leave a Comment

thirty four + = thirty five