I’m sure most people cringe when they hear that they have been assigned a task which has to do with dates in JavaScript. Because JavaScript is lacking a fully featured date library these tasks are rarely trivial and become even more difficult when you need to support users around the world.

Converting a timestamp to UTC time.

To display a timestamp in UTC around the world instead of in the users local timezone you use getTimezoneOffset, multiply it by 60,000 and then subtract that from your timestamp.

var rd = new Date.getTimezoneOffset()*60000,
    time = new Date((1349797266.032 * 1000) - rd);

console.log('UTC timestamp is ' + time);

Calculating the users timezone

To calculate the users timezone we need to determine the offset between the current time and the UTC time. To do that we use the getUTCHours method and the compare the two dates.

var dateATmp = new Date(2013, 0, 1, 0, 0, 0, 0),
    dateA = new Date(2013, 0, 1, dateATmp.getUTCHours(), 0, 0, 0);

console.log('Your timezone is GMT ' + (dateATmp - dateA) / 3600000);

Determining if the user observes daylight savings time

Calculating if the user observes daylight savings time (DST) is a little long winded but is certainly possible. We need to calculate the timezone difference between January and July. To do that we create the two dates, one in their current timezone and the other in UTC. We then divide the difference by 3600000 to get the hour offset and if they are the same DST is not observed.

var dateATmp = new Date(2013, 0, 1, 0, 0, 0, 0),
    dateA = new Date(2013, 0, 1, dateATmp.getUTCHours(), 0, 0, 0),
    dateBTmp = new Date(2013, 6, 1, 0, 0, 0, 0),
    dateB = new Date(2013, 6, 1, dateBTmp.getUTCHours(), 0, 0, 0),
    diffStdTime = (dateATmp - dateA) / 3600000,
    diffDaylightTime = (dateBTmp - dateB) / 3600000,
    dst = (diffStdTime == diffDaylightTime) ? 'not': '';

console.log('DST is %s observed here.', dst);

I hope that some or all of these solutions help make your life with dates in JavaScript a little easier. If you have any problems, or if you know of a better way to accomplish these tasks please let me know below or by mentioning me on twitter @fromanegg Thanks for reading!