Yashpal S
Yashpal S

Reputation: 319

How to convert local date (without time) in UTC DateTime in JavaScript

I am trying to convert the local date (without time) in UTC Date and pass it to server. Suppose I have a local date selected from Calendar which is 01-Jun-2021 and when converted to Date its Tue Jun 01 2021 00:00:00 GMT+0530.

My requirement is that, it should be converted to Mon May 31 2021 18:30:00 GMT+0530 and when sent to the server it should be Mon May 31 2021 18:30:00 only. I tried do that with below code and it give me the desired result. However when it is sent to the server its like 5/31/2021 1:00:00 PM in C#. My local develop machine is in IST Zone.

export const dateToUTC = (date: Date): Date => {
  let _date = new Date(
    date.getUTCFullYear(),
    date.getUTCMonth(),
    date.getUTCDate(),
    date.getUTCHours(),
    date.getUTCMinutes(),
    date.getUTCSeconds(),
    date.getUTCMilliseconds()
  );
  return _date;
};

Can anyone please help me this query? I think the main issue is GMT+0530 which is being passed to server. I can do some tweaks and paly with the offset value but it might not work always.

Upvotes: 0

Views: 417

Answers (1)

antanta
antanta

Reputation: 740

For your case I would suggest using moment.js library. The code would look like this:

// Moment wrapper object
var m = moment.parseZone('2021-06-01T00:00:00+05:30').utc();
// Default format
console.log(m.format()); // "2021-05-31T18:30:00Z"
// Your string for the server
console.log(m.format("ddd MMMM DD YYYY HH:mm:ss")); // Mon May 31 2021 18:30:00

JSFiddle

Indeed there is some tweaking underneath, but at least you can rely on it.

Upvotes: 1

Related Questions