Home > Enterprise >  Convert into DateTime format ISO8601
Convert into DateTime format ISO8601

Time:05-07

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;

CodePudding user response:

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))
);

CodePudding user response:

You can try to use

new Date('2022-05-05 18:08:13.311951  0:00').toISOString()
  • Related