-1

I'm receiving this kind of string as date "2020-09-09T12:41:41 -04:00". It seems like this string contains time offset. I need to convert this to "3/15/2020, 1:23:09 PM " format. How can I achieve this?

I tried to create new Date object with that string but it shows me Invalid Date.

RobG
  • 142,382
  • 31
  • 172
  • 209

1 Answers1

1

You can use INTL DateTime format after you remove the illegal space

const d = new Date("2020-09-09T12:41:41-04:00")
console.log(d)

const options = {
  year: "numeric",
  month: "numeric",
  day: "numeric",
  hour : "numeric",
  minute : "numeric",
  second : "numeric",
};
const dateString = new Intl.DateTimeFormat("en-US", options).format(d);
console.log(dateString);

Alternatively have full control

const toAMPM = hhmmss => {
  const [hours, minutes, seconds] = hhmmss.split(":");
  const formatHours = hours % 12 || 12;
  const ampm = hours < 12 ? "AM" : "PM";
  return `${+formatHours}:${minutes}:${seconds} ${ampm}`;
};
const convertTime = dateString => {
  const d = new Date(dateString).toISOString();
  const [_, yyyy, mm, dd, time] = d.match(/(\d{4})-(\d{2})-(\d{2})T(\d{2}:\d{2}:\d{2})\./);
  return `${+mm}/${+dd}/${yyyy}, ${toAMPM(time)}`;
};

console.log(convertTime("2023-02-28T12:41:41-04:00"));
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • While en-us is likely pretty stable, it's not a good idea in general to use *Intl.DateTimeFormat* where precise formatting is required. Recently, the format for language en-ca changed from y-MM-DD to M/d/y (reflecting a change by the CLDR) much to the [annoyance of some on SO](https://stackoverflow.com/questions/75562129/why-is-date-locale-en-ca-returning-m-d-yyyy-instead-of-yyyy-mm-dd#comment133315993_75562129). Apparently this was [an error](https://unicode-org.atlassian.net/browse/CLDR-16399), but it shows that the formatting is somewhat whimsical. – RobG Mar 04 '23 at 07:43