Joe Joe - 28 days ago 7
Javascript Question

How to convert javascript date to a particular timezone

I am getting date info as number in milliseconds. I am able to parse it properly. But when I change my pc timezone the parsed time is also changed. I want only to a particular timezone only.

EX.

Time in millisec: 1461645900000
Actual Parsed: 26-Apr-2016 10:15:00 IST


when pc timezone is changed it become:
Tue Apr 26 2016 14:15:00 GMT+0930 (Local Standard Time)


Here I want only the actual time. How to get it?

Here is My little try:

function parseDateTime(dt, format) {
var months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec" ];
var ret = "";
if (dt) {
var day="",month="",year="",hour="",mins="",secs="";
var d = new Date(dt)
var os=d.getTimezoneOffset();
if(os<0){

}
ret += d.getDate() + "-" + months[parseInt(d.getMonth())] + "-"
+ d.getFullYear() + " " + leftPad(d.getHours(), 2, "0") + ":"
+ leftPad(d.getMinutes(), 2, "0") + ":"
+ leftPad(d.getSeconds(), 2, "0");
}
document.getElementById("d1").innerHTML=ret;
console.log(ret);
}
function leftPad(number, targetLength, withWhat) {
var output = number + '';
while (output.length < targetLength) {
output = withWhat + output;
}
return output;
}
parseDateTime(1461645900000);


I have used
new Date().toLocaleString("en-US", {timeZone: ""}) but limited. Also I am not interested in new lib.

Answer

I understand that you wanted to get a same time irrespective of time zone when ever you pass the milliseconds.

instead of the following two lines

    var d = new Date(dt)
    var os = d.getTimezoneOffset();

you include the below lines

    var os = new Date()
    os = os.getTimezoneOffset();
    var d = new Date((dt + (os * 60 * 1000)));

This adjusts your milliseconds to UTC time based on your local timezone and creates the date object from the adjusted UTC time, so that you will always get same time, irrespective of your local time zone.

Comments