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

Time:05-14

I have specific DateTime values in this format 'YYYY-MM-DDThh:mm:ss.ms' (e.g. '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)).

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.

//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'

CodePudding user response:

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'

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'

CodePudding user response:

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

  • Related