mxy345
mxy345

Reputation: 3

How to convert this date format to JS Date?

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

Upvotes: 0

Views: 205

Answers (1)

mplungjan
mplungjan

Reputation: 177851

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)

Upvotes: 1

Related Questions