Convert string to datetime

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

Answer

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 = 
  `*FixedndateString2Date('01-01-2016 00:03:44'):n => ${
    dateString2Date('01-01-2016 00:03:44')}`;

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

result.textContent += 
  `nnWith formattingntryParseDateFromString('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>