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


Solution 1:

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.

Solution 2:

For this format (assuming datepart has the format dd-mm-yyyy) in plain javascript use dateString2Date.

[Edit] Added an ES6 utility method to parse a date string using a format string parameter (format) to inform the method about the position of date/month/year in the input string.

var result = document.querySelector('#result');

result.textContent = 
  `*Fixed\ndateString2Date('01-01-2016 00:03:44'):\n => ${
    dateString2Date('01-01-2016 00:03:44')}`;

result.textContent += 
  `\n\n*With formatting\ntryParseDateFromString('01-01-2016 00:03:44', 'dmy'):\n => ${
  tryParseDateFromString('01-01-2016 00:03:44', "dmy").toUTCString()}`;

result.textContent += 
  `\n\nWith formatting\ntryParseDateFromString('03/01/2016', 'mdy'):\n => ${
  tryParseDateFromString('03/01/1943', "mdy").toUTCString()}`;

// fixed format dd-mm-yyyy
function dateString2Date(dateString) {
  var dt  = dateString.split(/\-|\s/);
  return new Date(dt.slice(0,3).reverse().join('-') + ' ' + dt[3]);
}

// multiple formats (e.g. yyyy/mm/dd or mm-dd-yyyy etc.)
function tryParseDateFromString(dateStringCandidateValue, format = "ymd") {
  if (!dateStringCandidateValue) { return null; }
  let mapFormat = format
          .split("")
          .reduce(function (a, b, i) { a[b] = i; return a;}, {});
  const dateStr2Array = dateStringCandidateValue.split(/[ :\-\/]/g);
  const datePart = dateStr2Array.slice(0, 3);
  let datePartFormatted = [
          +datePart[mapFormat.y],
          +datePart[mapFormat.m]-1,
          +datePart[mapFormat.d] ];
  if (dateStr2Array.length > 3) {
      dateStr2Array.slice(3).forEach(t => datePartFormatted.push(+t));
  }
  // test date validity according to given [format]
  const dateTrial = new Date(Date.UTC.apply(null, datePartFormatted));
  return dateTrial && dateTrial.getFullYear() === datePartFormatted[0] &&
         dateTrial.getMonth() === datePartFormatted[1] &&
         dateTrial.getDate() === datePartFormatted[2]
            ? dateTrial :
            null;
}
<pre id="result"></pre>

Solution 3:

You could use the moment.js library.

Then simply:

var stringDate = '01-01-1970 00:03:44';
var momentDateObj = moment(stringDate);

Checkout their api also, helps with formatting, adding, subtracting (days, months, years, other moment objects).

I hope this helps.

Rhys

Solution 4:

http://www.w3schools.com/jsref/jsref_parse.asp

    <script type="text/javascript">
        var d = Date.parse("Jul 8, 2005");
        document.write(d);<br>
    </script>

Solution 5:

well, thought I should mention a solution I came across through some trying. Discovered whilst fixing a defect of someone comparing dates as strings.

new Date(Date.parse('01-01-1970 01:03:44'))