Hướng dẫn php detect browser timezone

This will get you the timezone as a PHP variable. I wrote a function using jQuery and PHP. This is tested, and does work!

Nội dung chính

  • Not the answer you're looking for? Browse other questions tagged php date date-time timestamp timezones or ask your own question.
  • Description
  • User Contributed Notes
  • Where can I see a working example of this plugin?

On the PHP page where you are want to have the timezone as a variable, have this snippet of code somewhere near the top of the page:

<?php    
    session_start();
    $timezone = $_SESSION['time'];
?>

This will read the session variable "time", which we are now about to create.

On the same page, in the <head> section, first of all you need to include jQuery:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

Also in the <head> section, paste this jQuery:

<script type="text/javascript">
    $(document).ready(function() {
        if("<?php echo $timezone; ?>".length==0){
            var visitortime = new Date();
            var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
            $.ajax({
                type: "GET",
                url: "http://example.com/timezone.php",
                data: 'time='+ visitortimezone,
                success: function(){
                    location.reload();
                }
            });
        }
    });
</script>

You may or may not have noticed, but you need to change the url to your actual domain.

One last thing. You are probably wondering what the heck timezone.php is. Well, it is simply this: (create a new file called timezone.php and point to it with the above url)

<?php
    session_start();
    $_SESSION['time'] = $_GET['time'];
?>

If this works correctly, it will first load the page, execute the JavaScript, and reload the page. You will then be able to read the $timezone variable and use it to your pleasure! It returns the current UTC/GMT time zone offset (GMT -7) or whatever timezone you are in.

You can read more about this on my blog

how can I get user Time Zone in Wordpress if you don't know where the user comes from.

Nội dung chính

  • Not the answer you're looking for? Browse other questions tagged php date date-time timestamp timezones or ask your own question.
  • Description
  • User Contributed Notes
  • Where can I see a working example of this plugin?

Let's say if a user is in USA I need to get USA Time Zone, if the user is in Germany I need to get Germany Time Zone.

asked Jun 25, 2021 at 7:50

6

Since WordPress is a server-side framework/CMS, it likely doesn't have the functionality you're looking for. If you're looking for ways to obtain this information, the most reliable would likely be to ask the user.

To make it as painless as possible for the user, this functionality could be achieved via client-side scripting (ie. JavaScript) where you attempt to infer the user's timezone:

-new Date().getTimezoneOffset()/60;

And then ask the user to confirm that it is the correct timezone. Keep in mind, client side code is run on the user's machine and can be disabled entirely.

answered Jun 25, 2021 at 18:45

Not the answer you're looking for? Browse other questions tagged php date date-time timestamp timezones or ask your own question.

Retrieves the timezone of the site as a string.


Description

Uses the timezone_string option to get a proper timezone name if available, otherwise falls back to a manual UTC ± offset.

Example return values:

  • ‘Europe/Rome’
  • ‘America/North_Dakota/New_Salem’
  • ‘UTC’
  • ‘-06:30’
  • ‘+00:00’
  • ‘+08:45’

Top ↑

Return

(string) PHP timezone name or a ±HH:MM offset.


Top ↑

Source

File: wp-includes/functions.php

function wp_timezone_string() {
	$timezone_string = get_option( 'timezone_string' );

	if ( $timezone_string ) {
		return $timezone_string;
	}

	$offset  = (float) get_option( 'gmt_offset' );
	$hours   = (int) $offset;
	$minutes = ( $offset - $hours );

	$sign      = ( $offset < 0 ) ? '-' : '+';
	$abs_hour  = abs( $hours );
	$abs_mins  = abs( $minutes * 60 );
	$tz_offset = sprintf( '%s%02d:%02d', $sign, $abs_hour, $abs_mins );

	return $tz_offset;
}

Expand full source code Collapse full source code View on Trac View on GitHub



Top ↑

Changelog

Changelog
VersionDescription
5.3.0 Introduced.

Top ↑

User Contributed Notes

  • Details
  • Reviews
  • Installation
  • Support
  • Development

This plugin retrieves the time zone of the client using “Automatic Timezone Detection Using JavaScript” (http://pellepim.bitbucket.org/jstz/) the first time that a client accesses the site, sets a cookie containing the client’s time zone on the client, and reloads the page. This cookie is then read by PHP and the date_default_timezone_set() function (requires PHP 5 >= 5.1.0) is used to set the default time zone for PHP scripts. Since it runs just after all of the plugins are loaded, it changes the time zone for all of the PHP that follows. It is useful in cases where one wants users to see certain posts on certain days. E.g., if the post slug contains the day number, like “xyz-daynr,” then the post can be specified by “$slug = ‘xyz’.date(j);” in a theme template. The cookie does not expire for ten years, but is reset if the user changes time zones. So, unless the user deletes cookies or moves the page reload only occurs once every ten years.

Copyright 2012-2015 M.D. Green, SaeSolved:: LLC

License

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.1. A note was posted in our forum stating that sites may experience problems if changing timezones using date_default_timezone_set. WP expects it to always be UTC and display of things in different timezones are achieved in other ways:
https://vip.wordpress.com/documentation/vip-development-tips-tricks/use-current_time-not-date_default_timezone_set/
https://weston.ruter.net/2013/04/02/do-not-change-the-default-timezone-from-utc-in-wordpress/

The author has not observed any problems on the sites on which this plugin has been tested. Based on the foregoing post, however,it would be wise to check that no date-related operations are going awry after activating this plugin — even though no problems have been observed with the sites tested.

  1. To do: Develop, if possible, a way to effect the use of methods, other than using the date_default_timezone_set() function, to produce the same functionality the plugin currently has.
  • Settings page.
  1. Extract the use-clients-timezone folder and place in the wp-content/plugins folder.

  2. Enable the plugin.

  3. Set the fallback time zone under Settings->Use Client’s Timezone. (The time zone to use if the script fails to get the client’s time zone.)

Where can I see a working example of this plugin?

http://prayercentral.net/devotionals/a-word-for-today/.

The information on the site (in the example “A Word for Today”) will be for the day of the client, not the day of the server (which it would be without the plugin).

You can test this by changing the time on your computer to be in a time zone which is in a different day. E.g., if you live in New York, change the time zone on your computer to that of Sydney. You should see the information (in the case of the example) for the next day. (Check a site like http://www.timeanddate.com/ to be sure to get a time zone which is in a different day than the one normally set on your computer.)

Thank you for this useful plugin, it works fine on WP 5.8.2. Please keep it maintained.

Does exactly what it says.

Read all 6 reviews

“Use Client's Time Zone” is open source software. The following people have contributed to this plugin.

Contributors

  • drmikegreen

1.1.4

Added advice to check that no dated-related operations were adversely impacted by this plugin.

1.1.3

Changed cookie path to be site-wide.

1.1.2

Changed JavaScript so that the page is not reloaded if cookies are not enabled on the client.

1.1

Method for obtaining client time zone changed from attempting to retrieve time zone of IP to setting a cookie containing the clients time zone, then reading that cookie.

1.0

Original release.