Reputation: 25275
I'm working with a service that gives me broadcast times for Television shows in Unix Time (seconds since midnight, January 1st, 1970, in Greenwich, England). I need to convert this, in javascript, to Eastern Standard time (USA). I need to account for daylight savings time, and for the fact that the client's clock may be set to something other than Eastern Standard time. I'm sure this code has been written before. Can anyone point me toward it?
Upvotes: 0
Views: 3849
Reputation: 25275
I wrote some code which will turn GMT milliseconds into a Date-like object which can be queried for eastern standard time values. It handles daylight savings.
ESTDate = function(millis){
if(isNaN(parseInt(millis))) {
throw new Error("ESTDate must be built using a number");
}
var MILLIS_PER_DAY = 1000 * 60 * 60 * 24;
var gmtDate = new Date(millis);
var clockSetDate = function(month){
var date = new Date(0);
date.setUTCFullYear(gmtDate.getUTCFullYear());
date.setUTCMonth(month);
date.setUTCHours(2);
while(date.getUTCDay() != "0"){
date.setTime(
date.getTime() + MILLIS_PER_DAY
);
};
return date;
}
var startStandarTimeDate = clockSetDate(2);
var endStandardTimeDate = clockSetDate(10);
date = new Date(millis);
var estOffset = 60 * 60 * 1000 * 4;
var dltOffset = (
(startStandarTimeDate < date) &&
(date < endStandardTimeDate)
) ? 0: 60 * 60 * 1000;
date.setTime(date.getTime() - (estOffset + dltOffset));
var self = {
getDate: function(){
return date.getUTCDate();
},
getDay:function(){
return date.getUTCDay();
},
getFullYear:function(){
return date.getUTCFullYear();
},
getHours:function(){
return date.getUTCHours();
},
getMilliseconds:function(){
return date.getUTCMilliseconds();
},
getMinutes:function(){
return date.getUTCMinutes();
},
getMonth:function(){
return date.getUTCMonth();
},
getSeconds:function(){
return date.getUTCSeconds();
}
}
return self;
}
Upvotes: 0
Reputation: 10449
https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6016329.html
Looks to have a solution for changing timezones, but it does look like you have to do the math yourself. There is no, setTimezone or setLocale method.
Upvotes: 0
Reputation: 31010
What you'll find is it's not possible to translate to a specific timezone, but as long as your users are in the desired timezone, this will work:
var date = new Date();
date.setTime(unixTime * 1000);
The resulting date object will display in the timezone of the computer running the browser:
window.console.log(date.toString())
yields:
"Thu Jun 25 2009 09:48:53 GMT-0400 (EDT)"
for me anyway)
Upvotes: 3