[SOLVED] Convert string to datetime

Issue

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

Solution

For this format (assuming datepart has the format dd-mm-yyyy) in plain javascript use dateString2Date. It may bite you, because of browser compatibility problems.

tryParseDateFromString is 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. The date is constructed using Date.UTC, circumventing the aforementioned browser compatibility problems.

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

// multiple formats (e.g. yyyy/mm/dd (ymd) or mm-dd-yyyy (mdy) etc.)
function tryParseDateFromString(dateStringCandidateValue, format = "ymd") {
  const candidate = (dateStringCandidateValue || ``)
    .split(/[ :\-\/]/g).map(Number).filter(v => !isNaN(v));
  const toDate = () => {
    format = [...format].reduce((acc, val, i) => ({ ...acc,  [val]: i }), {});
    const parts = 
      [candidate[format.y], candidate[format.m] - 1, candidate[format.d] ]
        .concat(candidate.length > 3 ? candidate.slice(3) : []);
    const checkDate = d => d.getDate && 
      ![d.getFullYear(), d.getMonth(), d.getDate()]
        .find( (v, i) => v !== parts[i] ) && d || undefined;
    
    return checkDate( new Date(Date.UTC(...parts)) );
  };

  return candidate.length < 3 ? undefined : toDate();
}

const 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 dmy
tryParseDateFromString('01-12-2016 00:03:44', 'dmy'):\n => ${
tryParseDateFromString('01-12-2016 00:03:44', "dmy").toUTCString()}`;

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

result.textContent +=
  `\n\n*With invalid format
tryParseDateFromString('12-13-2016 00:03:44', 'dmy'):\n => ${
tryParseDateFromString('12-13-2016 00:03:44', "dmy")}`;


result.textContent +=
  `\n\n*With formatting invalid string
tryParseDateFromString('03/01/null', 'mdy'):\n => ${
tryParseDateFromString('03/01/null', "mdy")}`;

result.textContent +=
  `\n\n*With formatting no parameters
tryParseDateFromString():\n => ${tryParseDateFromString()}`;
<pre id="result"></pre>

Answered By – KooiInc

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *