Reputation: 51917
I need a way to convert times in the future to different timezones without relying on the user's computer time.
At registration time, the user supplies his timezone. When he logs in, I calculate the offset in minutes between the UTC time and his time and inject that offset into the page so that a javascript function can do the conversions. Something like this:
var TheUTCTime = new Date(UserTime.getTime() - TimeZoneOffsetInMinutes * 60000);
and like this for the other way around:
var TheUserTime = new Date(UTCTime.getTime() + TimeZoneOffsetInMinutes * 60000);
This works really well to convert times as long as the offset doesn't change. For instance, because of daylight saving, between US EST and UTC, there's a difference of 300 minutes or 360 minutes depending on the month in the year.
My functions work well to convert today's date but I'd like something that can 1) do the same thing for any day of the year and 2) doesn't depend on the user's internal clock or timezone.
How could I do this?
Thanks.
Upvotes: 0
Views: 2966
Reputation: 1499770
My functions work well to convert today's date but I'd like something that can 1) do the same thing for any day of the year and 2) doesn't depend on the user's internal clock or timezone.
If you want to convert another UTC time into the user's local time, you have to know their time zone. That's pretty much the definition of a time zone: a mapping between UTC and local time (or equivalently, between UTC and the offset from local time).
As you've seen, getting the current offset isn't enough, because of daylight saving transitions (and any other changes to time zones - they vary more than you might expect).
Basically there's no way round this: you will have to ask the user for their time zone. You can make a good guess based on the current offset from UTC and possibly geocoding their IP address, but you'll have to confirm it with them. (For example, they may be on a trip or something, and not in their "home" time zone.)
Upvotes: 1
Reputation:
To don't depend on the user's clock timezone, I think the best approach is to do conversions in the server side
.
There's a good question here in the SO that covers daylight saving time and javascript Date object: Daylight saving time and time zone best practices
Upvotes: 0