How to convert string to date using JavaScript - examples! In this post we will cover various technics and show how to fix common errors like:
"Unable to convert '25-12-2020' into a date" or "Unable to convert "Invalid Date" into a date"!
So let us start, let's convert this string '25-12-2020' to date:
const testDate = '25-12-2020';
const formatDate = new Date(testDate);
console.log(formatDate);
Executing this code we will have error: "Unable to convert "Invalid Date" into a date"
The reason for this format of the string, you date should be structured in a way year-month-day and not day-mont-year. So if we change our string to: 2020-12-25 code will work fine:
const testDate = '2020-12-25';
const formatDate = new Date(testDate);
console.log(formatDate); // output: Fri Dec 25 2020 01:00:00 GMT+0100 (Central European Standard Time)
By using Angular you can achieve the same thing by using formatDate() method:
formatDate(range.start, 'yyyy-MM-dd', 'en');
As you saw in our latest output, date is in the user default time zone. Sometimes this can cause a trouble because if you have users from different timezones they will get different results.
So the best way is to convert the date in UTC format
Let's take a look this example:
const testDate = '2020-12-25 00:00:00';
const formatDate = new Date(testDate);
console.log(formatDate);// output: Fri Dec 25 2020 00:00:00 GMT+0100 (Central European Standard Time)
But if we convert this time into UTC, we will not only get different time but different date:
const testDate = '2020-12-25 00:00:00';
const formatDate = new Date(testDate).toUTCString();
console.log(formatDate); // output: Thu, 24 Dec 2020 23:00:00 GMT
we should keep this in mind when getting or parsing the dates from our users.
Happy 2021 🧨