06 November 2009

Javascript display time in browser local format

This is something i found useful and I'm sure I will again in the future.

Use coldfusion to set the UTC date and time. Then we'll have JS convert that time to the users local time.

Obviously it's preferable to have the user create an account and have them select their own, but in this case that wasn't an option.


function getDstOffset(myInputDate)
{
//get clients timezone offset so we can display in local format (60000 forces to use milliseconds)
var clientOffset = -myInputDate.getTimezoneOffset() * 60000;
return clientOffset;
}
function displayMyLocalTime(divname)
{
//take the passed in datetime(handled by server) and convert it to browser local
//this function takes the name of the dov to update with the datetime
var bigBenTime = new Date();

//set the js time to match that given to us by server
bigBenTime.setDate(#day(futuredate)#);
bigBenTime.setMonth(#month(futuredate)-1#);
bigBenTime.setYear(#year(futuredate)#);
bigBenTime.setHours(#hour(futuredate)#);
bigBenTime.setMinutes(#minute(futuredate)#);
bigBenTime.setSeconds(#second(futuredate)#);

cfif LEN(futureTime)
//time is defined, set it
bigBenTime.setHours(#hour(futuretime)#);
bigBenTime.setMinutes(#minute(futuretime)#);
bigBenTime.setSeconds(#second(futuretime)#);
/cfif

///get milliseconds since epoc and milliseconds of timezoneoffset
localBenTime = bigBenTime.getTime() + (getDstOffset(bigBenTime));

//put milliseconds back into useful format
benTime = new Date(localBenTime);

//set div to time
$(divname).innerHTML = benTime;
}

No comments: