Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically detect user's current local time with JavaScript or PHP

I often need to display information based on or influenced by a user's actual local time which differs across time zones. Is there a reliable way of getting a user's current time and/or timezone?

Key Issues:

  • Server-side code is based on the website host or user's ISP
  • Client-side code is based on the user's system clock which is too easily manipulated

Key questions:

  • Is it necessary to pinpoint a user's geo-location?
  • Can the ISP time be an accurate guide?
  • Users OS clocks can vary or be modified by users?

Examples:

Countdown:

Only 1 hour, 3 minutes, 56 seconds to go!

Issue: seconds to go based on what; The user's OS clock, the hosts server time (plus or minus offset), ISP system time. This is easy if the clock finishes at the same time for all timezones, but trickier if it's a countdown to something like midnight in the user's local time zone)

Edit log

Item posted at 3:03pm (10 seconds ago)

Issue: "10 seconds" is calculated regardless of user, the time is adjusted to match the user's time zone.

Opening times:

This restaurant is open now until midnight (AEST).

Issue: Giving a time such as midnight can be calculated by offsetting from the server-side but using psudo times such as now, in 2 hours is based on the user's time.

PHP: using time() outputs the server time. This can be offset depending on the user's timezone.

JavaScript: using Date() outputs the user's computer clock time which is too easily manipulated.

like image 260
Peter Craig Avatar asked May 14 '09 13:05

Peter Craig


1 Answers

With JavaScript, there is a way to get the users current timezone offset.

new Date().getTimezoneOffset() * -1

returns the offset in minutes from GMT. Do not store this value as it can change depending on Daylight Saving Time. If you need it on the server (php) then you'll need to capture it in send it.

Unfortunately, the HTTP spec doesn't send the users timezone as a header, which is what php would need.

like image 58
Jason Harwig Avatar answered Oct 09 '22 02:10

Jason Harwig