简体   繁体   English

如何在不以不同格式结束的情况下将 UTC DateTime 转换为本地 DateTime

[英]How do I convert UTC DateTime to local DateTime without ending up with a different format

I have specific DateTime values in this format ' YYYY-MM-DDThh:mm:ss.ms ' (eg ' 2022-05-10T13:44:00.0000000 ') and I need to convert them to local DateTime (which is UTC+2 for me) without changing the format (so ' 2022-05-10T15:44:00.0000000 ' is the desired result (even better would be without the milliseconds but that would just be the icing on the cake)).我有这种格式的特定日期时间值“ YYYY-MM-DDThh:mm:ss.ms ”(例如“ 2022-05-10T13:44:00.0000000 ”),我需要将它们转换为本地日期时间(UTC+2对我来说)而不改变格式(所以' 2022-05-10T15:44:00.0000000 '是期望的结果(如果没有毫秒会更好,但这只是锦上添花))。

I've searched far and wide but every alleged solution I find either changes the format or doesn't change the time at all.我进行了广泛的搜索,但我发现的每一个所谓的解决方案要么改变格式,要么根本不改变时间。

This is what I have right now, it successfully converts the time to local time but by running it through.toISOString() to get the original format back it converts it back to UTC time.这就是我现在所拥有的,它成功地将时间转换为本地时间,但是通过运行它 through.toISOString() 以恢复原始格式,它将它转换回 UTC 时间。

//Input: event.start.dateTime = '2022-05-10T13:44:00.0000000'

let startDateTime = new Date(event.start.dateTime);
startDateTime.setMinutes(startDateTime.getMinutes() - 
startDateTime.getTimezoneOffset());
document.getElementById('ev-start').value = 
startDateTime.toISOString().slice(0,16);

//Output: '2022-05-10T13:44:00.000Z'

I couldn't find a clean and satisfying solution so I decided to just to the formatting myself.我找不到一个干净和令人满意的解决方案,所以我决定自己格式化。 Here's what I ended up with:这是我最终得到的:

Input: ' 2022-05-10T13:44:00.0000000 '输入:' 2022-05-10T13:44:00.0000000 '

let startDateTime = new Date(event.start.dateTime);
startDateTime.setMinutes(startDateTime.getMinutes() - 
startDateTime.getTimezoneOffset());
let localStartDateTime = startDateTime.getFullYear() + "-" + 
       (startDateTime.getMonth() + 1).toString().padStart(2, '0') +
       "-" + startDateTime.getDate().toString().padStart(2, '0') + 
       "T" + startDateTime.getHours().toString().padStart(2, '0') + 
       ":" + startDateTime.getMinutes().toString().padStart(2, '0') 
       + ":" +
       startDateTime.getSeconds().toString().padStart(2, '0');
       document.getElementById('ev-start').value = 
       localStartDateTime;

Output: ' 2022-05-10T15:44:00 ' Output:“ 2022-05-10T15:44:00

Hope this helps希望这可以帮助

 const startDateTime = new Date('2022-05-10T13:44:00.0000000'); const outputDateTime = new Date(startDateTime.toString()).toISOString().slice(0, 19); //document.getElementById('ev-start').value = outputDateTime console.log(outputDateTime);

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

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