0

I'm working with a service that provides a weird date format that I just can not figure out an concise way of converting to a JS Date Object. I need to perform some logic with the dates which is why I need to convert it.

The date format returned by the service is like so: 02/Dec/2020:23:58:15 +0000.

Any help highly appreciated, thanks in advance

mxy345
  • 3
  • 1

1 Answers1

1

The date parses if you replace the first : with space

const str = "02/Dec/2020:23:58:15 +0000"

console.log(new Date(str.replace(/:/," "))); // change only the first colon

For a safer version it seems we need to do this - tested in Safari, Chrome and Firefox

const monthNames = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
const re = /(\d{2})\/(\w{3})\/(\d{4}):(\d{2}):(\d{2}):(\d{2}) (.*)/;

const makeDate = str => {
  const [_, dd, mmm, yyyy, hh, min, ss, tz] = str.match(re)
  const tzStr = [tz.slice(0, 3), ':', tz.slice(3)].join(''); // make ±hh:mm
  const mm = monthNames.indexOf(mmm.toLowerCase()); // English only
  const isoString = `${yyyy}-${mm}-${dd}T${hh}:${min}:${ss}${tzStr}`
  console.log(isoString)
  return new Date(isoString)
};

const str = "02/Dec/2020:23:58:15 +0000"
const d = makeDate(str);
console.log(d)
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 1
    In Safari, both return null. See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) Also, the use of *Date.parse* in `new Date(Date.parse(expression))` is redundant. – RobG Dec 03 '20 at 22:07
  • 1
    It works but only because the offset in the timestamp is "+0000". An offset like "+0530" or "-0330" would be an issue. Also not sure about cases where applying the offset causes the date and time to cross a daylight saving boundary. That's the kind of rare issue (so called "edge case") that is really hard to find. – RobG Dec 04 '20 at 22:59
  • @RobG My latest version works in Chrome, Safari and Firefox – mplungjan Dec 05 '20 at 07:33