Skip to content
Advertisement

Convert string to datetime

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

Advertisement

Answer

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.

See also

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

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

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

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


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

result.textContent +=
  `nn*With formatting no parameters
tryParseDateFromString():n => ${tryParseDateFromString()}`;
<pre id="result"></pre>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement