EN
JavaScript - convert string to datetime
0
points
In this article, we would like to show you how to convert string to datetime in JavaScript.
Quick solution:
let text = '2021-07-28 17:55:11';
let date = new Date('2021-07-28 17:55:11');
console.log(date); // Wed Jul 28 2021 17:55:11 GMT+0200 (Central European Summer Time)
Note:
The string format has to be
YYYY-MM-DD
(ISO 8601 format).
Practical example
In this example, we present how to convert various strings to the datetime format.
// ONLINE-RUNNER:browser;
let string1 = '2021-07-28 17:55:11';
let string2 = '2021 Jul 28 17:55:11';
let string3 = '2021/7/28 17:55:11';
let date1 = new Date(string1);
let date2 = new Date(string2);
let date3 = new Date(string3);
console.log(date1); // Wed Jul 28 2021 17:55:11 GMT+0200 (Central European Summer Time)
console.log(date2); // Wed Jul 28 2021 17:55:11 GMT+0200 (Central European Summer Time)
console.log(date3); // Wed Jul 28 2021 17:55:11 GMT+0200 (Central European Summer Time)
Example invalid string formats:
// ONLINE-RUNNER:browser;
let string1 = '28-07-2021 17:55:11';
let string2 = '2021/28/07 17:55:11';
let date1 = new Date(string1);
let date2 = new Date(string2);
console.log(date1); // Invalid Date
console.log(date2); // Invalid Date