0

I have tried goggling the results to convert data &time in pst to utc time zone.I couldn't find any.Could anyone pls help me how to achieve this.Thank you.

balaji
  • 57
  • 1
  • 9

1 Answers1

0

Someone mentioned a link in the comments: Convert date to another timezone in JavaScript

That answer deals with timezones explicitly. I favor another approach: if you call new Date().getTime() you will always get the milliseconds in UTC. Then, no matter what timezone you're in when you reconstruct your date, you can use code like the following:

var offsetMillis = -date.getTimezoneOffset() * 60000;

function convertToDate(){
  var utcMillis = document.getElementById('leftMillis').value;
  var x = new Number(utcMillis);
  var date = new Date(x);
  document.getElementById('leftDate').value=date.toDateString()+' '+date.toLocaleTimeString();
  x -= offsetMillis;
  date = new Date(x);
  document.getElementById('leftUTCDate').value=date.toDateString()+' '+date.toLocaleTimeString();
}

What you're doing is to subtract the offset to UTC from the current UTC millis. I like this option because it deals with the string formatting nicely.

Paste some UTC milliseconds in the left column of that site to see that code in action.

Another option (and probably the more standard one?) is to simply construct the date: new Date(millis) and then use the UTC methods from the date: getUTCHours(), etc.

Community
  • 1
  • 1
Sandman
  • 2,577
  • 2
  • 21
  • 32