-1

I'm trying to convert a date format into another format in javascript.

Current format : 3/17/2021, 2:23:24 PM Required format : 2021-03-17T14:23:24.000Z

How to do this in javascript?

In chrome, it is working fine using new Date(), but it is not working in firefox browser.

skp
  • 43
  • 10
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString – Sirko Mar 17 '21 at 09:00
  • Presumably you're doing `new Date('3/17/2021, 2:23:24 PM')`, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Mar 17 '21 at 09:02

2 Answers2

2

You can parse the string to a Date then use toISOString, but beware of the built–in parser, see Why does Date.parse give incorrect results?. Note that this will also parse the string as local, then produce a UTC timestamp.

Alternatively you can parse the string manually and just reformat the parts, it it's already UTC, or parse it as local and produce a UTC timestamp, e.g.

// No Date object
// Reformat  3/17/2021, 2:23:24 PM as ISO 8601 assuming input is UTC
function reformatDate0(d) {
  let [M, D, Y, h, m, s, ap] = d.trim().split(/\W+/);
  let z = n => ('0'+n).slice(-2);
  return `${Y}-${z(M)}-${z(D)}T${z((h%12) + (/am/i.test(ap)?0:12))}:${m}:${s}.000Z`;
}

console.log('0: ' + reformatDate0('3/17/2021, 2:23:24 PM'));

// Using a Date object, values as UTC
// Reformat  3/17/2021, 2:23:24 PM as ISO 8601 assuming input is UTC
function reformatDate1(d) {
  let [M, D, Y, h, m, s, ap] = d.trim().split(/\W+/);
  return new Date(
    Date.UTC(Y, M-1, D, (h%12) + (/am/i.test(ap)?0:12), m, s)
  ).toISOString();
}

console.log('1: ' + reformatDate1('3/17/2021, 2:23:24 PM'));

// Using a Date object, values as local
// Reformat  3/17/2021, 2:23:24 PM as ISO 8601 assuming input is local
function reformatDate2(d) {
  let [M, D, Y, h, m, s, ap] = d.trim().split(/\W+/);
  return new Date(Y, M-1, D, (h%12) + (/am/i.test(ap)?0:12), m, s).toISOString();
}

console.log('2: ' + reformatDate2('3/17/2021, 2:23:24 PM'));

Note that the first two treat the input at UTC, last treats it as local so the time is shifted by the host timezone offset for the input date and time.

RobG
  • 142,382
  • 31
  • 172
  • 209
0

You need to convert the string to a Date, then to convert the Date to a simplified extended ISO format (you can use the toISOString() method):

my_date = new Date("3/17/2021 2:23:24 PM");
my_date.toISOString(); // "2021-03-17T13:23:24.000Z"
Ahmad MOUSSA
  • 2,729
  • 19
  • 31
  • Re "*you need to…*", not necessarily. The string should be parsed manually, not with the built–in parser, and a suitable format can be generated directly from the parts without creating a Date object. – RobG Mar 18 '21 at 00:57