EN
TypeScript - convert string to datetime
0
points
In this article, we would like to show you how to convert string to datetime in TypeScript.
Quick solution:
const text: string = '2021-07-28 17:55:11';
const date: Date = new Date('2021-07-28 17:55:11');
console.log(date); // 2021-07-28T15:55:11.000Z
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.
const string1: string = '2021-07-28 17:55:11';
const string2: string = '2021 Jul 28 17:55:11';
const string3: string = '2021/7/28 17:55:11';
const date1: Date = new Date(string1);
const date2: Date = new Date(string2);
const date3: Date = new Date(string3);
console.log(date1); // 2021-07-28T15:55:11.000Z
console.log(date2); // 2021-07-28T15:55:11.000Z
console.log(date3); // 2021-07-28T15:55:11.000Z
Example invalid string formats:
const string1: string = '28-07-2021 17:55:11';
const string2: string = '2021/28/07 17:55:11';
const date1: Date = new Date(string1);
const date2: Date = new Date(string2);
console.log(date1); // Invalid Date
console.log(date2); // Invalid Date