2

I am working on a web application where a user can set his/her timezone in the application which is further used in the application for various date-time conversions. The selected timezone can be different from user's locale timezone.

I am currently stuck on a problem where I need to compare a user selected date(which user assumes to be in the timezone selected by him/her in the application) with the current date to see if the selected date is a date in future. With reference to all the places I have searched, I have found that I can get current date in user locale or UTC time.

So the gist of my problem is - Is there any way to convert a date from one timezone to another using the timezone abbreviations?

I have searched a lot before posting here but could not get any solution. Most of the places that I found during my search suggest that there is no such solution available.

I have tried using date.js but it does not suffice the purpose as it is quite outdated and also the timezone abbreviations supported by it is a very limited set. I have also taken a look a timezoneJS but I don't think that it works with timezone abbreviations.

Is there any way in which it can be accomplished using javascript or jquery?

Nisha Goyal
  • 37
  • 3
  • 10

1 Answers1

3

Here you go:

// calculate local time in a different city given the city's UTC offset
function calcTime(city, offset) {

    // create Date object for current location
    var date = new Date();

    // convert to msec
    // add local time zone offset 
    // get UTC time in msec
    var utc = date.getTime() + (date.getTimezoneOffset() * 60000);

    // create new Date object for different city
    // using supplied offset
    var newDate = new Date(utc + (3600000 * offset));

    // return time as a string
    return "The local time in " + city + " is " + newDate.toLocaleString();
}

// get Bombay time
console.log(calcTime('Bombay', '+5.5'));

// get Singapore time
console.log(calcTime('Singapore', '+8'));

// get London time
console.log(calcTime('London', '+1'));
mikemaccana
  • 110,530
  • 99
  • 389
  • 494
  • 1
    thanks for the answer... it works for all the timezones where day light saving is not active. Please tell me, how to get it working for timezones with daylight saving? – Nisha Goyal Jun 13 '13 at 11:34
  • Yes. It is not a built in Jscript fuction. Its a calculated conversion. –  Jun 13 '13 at 11:41
  • If you are using timezone-js then this is the code: var dt = new timezoneJS.Date("2012/04/10 10:10:30 +0000", 'Europe/London'); dt.setTimezone("Asia/Jakarta"); console.debug(dt); //return formatted date-time in asia/jakarta –  Jun 13 '13 at 11:45
  • Yeah I got that its a calculated conversion but is there a way to determine that daylight saving should be on for current time? No I am not using timezoneJS, it does not suit my needs. – Nisha Goyal Jun 13 '13 at 11:51