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:
xxxxxxxxxx
1
let text = '2021-07-28 17:55:11';
2
let date = new Date('2021-07-28 17:55:11');
3
4
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).
In this example, we present how to convert various strings to the datetime format.
xxxxxxxxxx
1
let string1 = '2021-07-28 17:55:11';
2
let string2 = '2021 Jul 28 17:55:11';
3
let string3 = '2021/7/28 17:55:11';
4
5
let date1 = new Date(string1);
6
let date2 = new Date(string2);
7
let date3 = new Date(string3);
8
9
console.log(date1); // Wed Jul 28 2021 17:55:11 GMT+0200 (Central European Summer Time)
10
console.log(date2); // Wed Jul 28 2021 17:55:11 GMT+0200 (Central European Summer Time)
11
console.log(date3); // Wed Jul 28 2021 17:55:11 GMT+0200 (Central European Summer Time)
Example invalid string formats:
xxxxxxxxxx
1
let string1 = '28-07-2021 17:55:11';
2
let string2 = '2021/28/07 17:55:11';
3
4
let date1 = new Date(string1);
5
let date2 = new Date(string2);
6
7
console.log(date1); // Invalid Date
8
console.log(date2); // Invalid Date