Reputation: 37
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?
Upvotes: 2
Views: 8385
Reputation:
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'));
Upvotes: 3