era s'q
era s'q

Reputation: 591

How to convert any timezone to local timezone in javascript?

The below code converts the date to local timezone:

function convertDateToServerDate(incomingDate) {
 var serverOffset = new Date();
 serverOffset = serverOffset.getTimezoneOffset();
 var outgoingServerDate = new Date((incomingDate.getTime() + Math.abs(serverOffset * 60 * 1000)));
 return outgoingServerDate;
}

I have a date in the IST timezone. I'm also in the IST timezone the above function changes the time whereas it should just return it. I also tried converting to UTC then back to the local but the same result. How to get a local timezone and do nothing if the date is already in local time zone?

Upvotes: 1

Views: 1591

Answers (3)

mplungjan
mplungjan

Reputation: 177685

The server offset has to be set using INTL, hardcoded or come from the server

So something like this

const serverOffset = -240; // this is static
function convertDateToServerDate(incomingDate) {
  const incomingOffset = incomingDate.getTimezoneOffset();
  if (serverOffset === incomingOffset) return incomingDate;
  console.log(serverOffset-incomingOffset,"difference")
  const outGoingDate = new Date(incomingDate.getTime())
  outGoingDate.setTime(incomingDate.getTime() + ((serverOffset-incomingOffset) * 60 * 1000));
  return outGoingDate;
}

console.log(convertDateToServerDate(new Date()))

Upvotes: 1

Tom
Tom

Reputation: 9127

You can't do this with vanilla Javascript without a library, because the Date class only comprehends two timezones: GMT, and local. (Source]

Libraries like momentjs and date-fns do not merely provide convenient functions, they very importantly also include hard-coded datasets that specify current real-world facts about time zone adjustments, including things like the dates where DST switches. This is vital, because if you look at the map of timezones, you'll see that the boundaries of the different zones are not straight lines. That's because they are determined by humans who made interesting compromises which are then enshrined in custom and law.

Many of those compromises are there so that people who share a jurisdiction can also share a clock. It would be enormously inconvenient for them otherwise, and many people would be adversely impacted every single day.

There is a proposal for a successor to Date, called Temporal, that would remedy this.

Upvotes: 4

Kuldeep Singh
Kuldeep Singh

Reputation: 46

Best to use moment library. https://momentjs.com/timezone/docs/

moment().tz(String)

var a = moment.utc("2013-11-18 11:55").tz("Asia/Taipei");

var b = moment.utc("2013-11-18 11:55").tz("America/Toronto");

a.format(); // 2013-11-18T19:55:00+08:00

b.format(); // 2013-11-18T06:55:00-05:00

a.utc().format(); // 2013-11-18T11:55Z

b.utc().format(); // 2013-11-18T11:55Z

Upvotes: 1

Related Questions