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

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

我有这种格式的特定日期时间值'YYYY-MM-DDThh:mm:ss.ms'(例如'2022-05- 10T13:44:00.0000000'),我需要在不更改格式的情况下将它们转换为本地日期时间(对我来说是 UTC+2)(所以 '2022-05-10T15:44: 00.0000000' 是期望的结果(没有毫秒会更好,但这只是锦上添花)。

我进行了广泛的搜索,但我发现的每一个所谓的解决方案要么改变了格式,要么根本没有改变时间。

这就是我现在拥有的,它成功地将时间转换为本地时间,但是通过 运行 它通过 .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'

我找不到干净且令人满意的解决方案,所以我决定自己格式化。这是我最终得到的结果:

输入:'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;

输出:'2022-05-10T15:44:00'

希望对您有所帮助

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