-1

I am receiving the input date as below.

2022-05-05 18:08:13.311951 +0:00

And I am trying to convert this to below format which follows ISO8601 format.

2022-05-05T18:08:13.311951+00:00

Is there a way in JS we can implement this logic. I know the equivalent sql query which is like below to achieve it but confused on the js to achieve same.

select to_char(CREATE_DT,'YYYY-MM-DD"T"hh24:mi:sstzh:tzm') CREATE_DT from TABLE_NAME;
Karu
  • 61
  • 7
  • 1
    It seems simple enough to write some code to just add a `T` and remove some whitespace. Have you tried doing that? – Liam May 06 '22 at 14:45
  • I tried that. let s = '2022-05-05 18:08:13.311951 +0:00' const d =s.split(' ') let str = '' str +=d[0] str +='T' str +=d[1] str +=d[2] How can I format the time designator as hh:mm in this case like 00:00 – Karu May 06 '22 at 14:46

1 Answers1

0

You can try a regular expression, however it might be a little complex and not that maintainable. An alternative is to parse the string into its parts and reconstruct it, e.g.

// Format 2022-05-05 18:08:13.311951 +0:00 as
//        2022-05-05T18:08:13.311951+00:00
function reformatTimestamp (ts) {
  let pad = c => c.padStart(2,'0');
  // Match one or more digits OR space followed by + or -
  let [Y, M, D, H, m, s, ms, oSign, oH, om] = ts.match(/\d+| [-+]/g) || [];
  return `${Y}-${M}-${D}T${H}:${m}:${s}.${ms}${oSign.trim()}${pad(oH)}:${om}`;
}  
  
  
['2022-05-05 18:08:13.311951 -8:00',
 '2022-05-05 18:08:13.311951 +5:30',
 '2022-05-05 18:08:13.311951 -10:00',
 '2022-05-05 18:08:13.311951 +10:00'].forEach(ts =>
   console.log(ts + '\n' +  reformatTimestamp(ts))
);
RobG
  • 142,382
  • 31
  • 172
  • 209