Languages
[Edit]
EN

JavaScript - convert string to datetime

0 points
Created by:
user4838
668

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
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - String (popular problems)

JavaScript - convert string to datetime
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join