简体   繁体   English

转换成日期时间格式 ISO8601

[英]Convert into DateTime format ISO8601

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.我正在尝试将其转换为遵循 ISO8601 格式的以下格式。

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

Is there a way in JS we can implement this logic.有没有办法在 JS 中实现这个逻辑。 I know the equivalent sql query which is like below to achieve it but confused on the js to achieve same.我知道等效的 sql 查询如下所示实现它但在 js 上混淆以实现相同。

select to_char(CREATE_DT,'YYYY-MM-DD"T"hh24:mi:sstzh:tzm') CREATE_DT from TABLE_NAME;

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, eg另一种方法是将字符串解析成它的部分并重建它,例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM