Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to datetime

How to convert string like '01-01-1970 00:03:44' to datetime?

like image 383
Damir Avatar asked Apr 01 '11 07:04

Damir


People also ask

Can we convert string to date in SQL?

In SQL Server, converting a string to date explicitly can be achieved using CONVERT(). CAST() and PARSE() functions.


1 Answers

Keep it simple with new Date(string). This should do it...

const s = '01-01-1970 00:03:44'; const d = new Date(s); console.log(d); // ---> Thu Jan 01 1970 00:03:44 GMT-0500 (Eastern Standard Time) 

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date


EDIT: "Code Different" left a valuable comment that MDN no longer recommends using Date as a constructor like this due to browser differences. While the code above works fine in Chrome (v87.0.x) and Edge (v87.0.x), it gives an "Invalid Date" error in Firefox (v84.0.2).

One way to work around this is to make sure your string is in the more universal format of YYYY-MM-DD (obligatory xkcd), e.g., const s = '1970-01-01 00:03:44';, which seems to work in the three major browsers, but this doesn't exactly answer the original question.

like image 56
Luke Avatar answered Sep 20 '22 18:09

Luke