I'm trying to get the user's timezone as a string on singup. example:
$timezone = "Asia/Tel_Aviv";
While researching the issue, I got how to Get timezone offset with Javascript, but I'm still unclear about how can I translate the timezone offset to a timezone string in php, as shown above?
Or, which other method cas I use in Javascript / PHP for getting the timezone string for each user?
I'm really not sure how to approach this.
You can't do this in PHP alone.
You can use Javascript to set the value in a cookie, then use PHP to read the cookie on the next page (re)load.
Javascript:
var dateVar = new Date()
var offset = dateVar.getTimezoneOffset();
document.cookie = "offset="+offset;
PHP:
echo $_COOKIE['offset'];
Use this to convert the offset to the friendly timezone name in PHP. Javascript returns the offset in minutes, while this PHP function expects the input to be in seconds - so multiply by 60. The third parameter is a boolean value of whether or not you are in Daylight Savings Time. Read the manual and update the code to fit your needs.
echo timezone_name_from_abbr("", intval($_COOKIE['offset'])*60, 0);
http://php.net/manual/en/function.timezone-name-from-abbr.php
You cannot get the timezone name from an offset. That's because there are many timezones which have the same offset at any given time, so you can't pick one based on an offset. (If you do, this will bite you in the butt later when the timezone goes into or out of DST, changing the offset.
Your best bet is to do geolocation by IP address (google it, lots of material out there) as a best first guess and then give the user an option to choose his timezone himself.
function tzone(){
if(isset($_SESSION["tz"])){ $return = $_SESSION["tz"]; } else {
$ip = $_SERVER["REMOTE_ADDR"];
$getip = file_get_contents("http://freegeoip.net/json/$ip");
$getip = json_decode($getip);
$lat = $getip->latitude; $lng = $getip->longitude; $country = $getip->country_name;
$getzone = file_get_contents("http://api.geonames.org/timezoneJSON?lat=$lat&lng=$lng&username=demo"); //you can change "demo" to your own username. its free service
$getzone = json_decode($getzone);
$zone = $getzone->timezoneId;
$_SESSION["tz"] = $zone;
$return = $_SESSION["tz"];
}
return $return;
}
You need to follow answers of Nicholas Pickering and deceze♦ partially. Do not use PHP's timezone_name_from_abbr function(Ref).
Follow these steps to get UTC time of any timezone set in user system:
Javascript (client-side):
var dateVar = new Date();
var offset = dateVar.getTimezoneOffset();
//getTimezoneOffset - returns the timezone difference between UTC and Local Time
document.cookie = "offset="+offset;
Php (server-side):
public function convert_utc_time($date)
{
$time_difference = isset($_COOKIE['offset'])?$_COOKIE['offset']:'';
if($time_difference != ''){
$time = strtotime($date);
$time = $time + ($time_difference*60); //minutes * 60 seconds
$date = date("Y-m-d H:i:s", $time);
} //on failure of js, default timezone is set as UTC below
return $date;
}
..
..
//in my function
$timezone = 'UTC';
$date = $this->convert_utc_time($post_date); //$post_date('Y-m-d H:i:s')
echo strtotime($date. ' '. $timezone)
Related
$offset = "<script>document.write(new Date().getTimezoneOffset().toString());</script>";
Session::set("offset", $offset);
$offset=Session::get("offset");
echo intval($offset);
I am trying to convert timezone to integer. intval output is always 0.
Try this
Session::set("time", time());
Then you can get your offset in next request:
$time=Session::get("time");
echo $time;
If you need to use TimeZone then you can use Carbon instance since you're using Laravel.
$time = Carbon::now();
$timeZone = $time->timezone;
Session::put('timezone', $timeZone);
and then retrieve the timezone from session....
$offset = "<script>document.write(new Date().getTimezoneOffset().toString());</script>";
Session::set("offset", $offset);
This means=
Session::set("offset", "<script>document.write(new Date().getTimezoneOffset().toString());</script>");
So your offset value is just a string "< script>document.write(new Date().getTimezoneOffset().toString());< /script>"
Your question should be how to get user timezone which is duplicate.
Determine a User's Timezone
get user timezone
I have a formatted address of a place like Bhubaneswar,Odisha,India.How can I get the Time Zone of this place ie "Asia/Calcutta" in php code ?
I can get this using googlemapapi ie Firstly i get the lat and long from this address and using this latitude and longitude and google time zone api key I get the time Zone in javascript .
I want the time zone in purely php code . Can i ?
Thanks in Avd
Sure you can. Try with file_get_contents():
<?php
$url = "https://maps.googleapis.com/maps/api/timezone/json?location=20,85×tamp=1393575206&sensor=false";
$json_timezone = file_get_contents($url);
print_r($json_timezone);
?>
This will print:
{ "dstOffset" : 0, "rawOffset" : 19800, "status" : "OK", "timeZoneId" : "Asia/Calcutta", "timeZoneName" : "India Standard Time" }
Replace the timestamp by the current timestamp or the timestamp corresponding to the date/time you want.
Getting User Timezone using PHP and JS (No API's) (Update on 2020)
Detecting user timezone is a two-step process:
Get the timezone offset of the browser with Javascript, and sent it to PHP (via AJAX or something).
Convert the timezone offset to a valid TZ Database timezone name such as America/New_York,Asia/Kolkata.
1) Getting the Browser Timezone Offset
Javascript has a getTimezoneOffset method which gives timezone difference, in minutes, from current local time to UTC. We need to pass this offset to the server.
It should be noted that getTimezoneOffset returns an offset which is positive if the local timezone is behind UTC and negative if it is ahead. So we must add an opposite sign (+ or -) to the offset.
var timezone_offset_minutes = new Date().getTimezoneOffset();
timezone_offset_minutes = timezone_offset_minutes == 0 ? 0 : -timezone_offset_minutes;
// Timezone difference in minutes such as 330 or -360 or 0
console.log(timezone_offset_minutes);
2) In PHP, Convert Timezone Offset in Minutes to a Timezone Name
You can get the timezone name from timezone offset in minutes through the timezone_name_from_abbr function.
// This is just an example. In application this will come from Javascript (via an AJAX or something)
$timezone_offset_minutes = 330; // $_GET['timezone_offset_minutes']
// Convert minutes to seconds
$timezone_name = timezone_name_from_abbr("", $timezone_offset_minutes*60, false);
// Asia/Kolkata
echo $timezone_name;
Now when you get the timezone name, you can get date and time relative to the user's timezone :
date_default_timezone_set($timezone_name);
Source: https://usefulangle.com/post/31/detect-user-browser-timezone-name-in-php
public function getTimezone($location)
{
$location = urlencode($location);
$APIkey = "PLACE API KEY HERE";
if(!$APIkey){ return false;}
$url = "https://maps.googleapis.com/maps/api/geocode/json?address={$location}&key=$APIkey";
$data = file_get_contents($url);
// Get the lat/lng out of the data
$data = json_decode($data);
if(!$data) return false;
if(!is_array($data->results)) return false;
if(!isset($data->results[0])) return false;
if(!is_object($data->results[0])) return false;
if(!is_object($data->results[0]->geometry)) return false;
if(!is_object($data->results[0]->geometry->location)) return false;
if(!is_numeric($data->results[0]->geometry->location->lat)) return false;
if(!is_numeric($data->results[0]->geometry->location->lng)) return false;
$lat = $data->results[0]->geometry->location->lat;
$lng = $data->results[0]->geometry->location->lng;
// get the API response for the timezone
//$timezoneAPI = "https://maps.googleapis.com/maps/api/timezone/json?location={$lat},{$lng}×tamp=1331161200&key=AIzaSyBtEwgQX2k0fijo3EsFlOLgXxEvkDpDyeI";
$timezoneAPI = "http://api.geonames.org/timezoneJSON?lat={$lat}&lng={$lng}&username=demo";
$response = file_get_contents($timezoneAPI);
if(!$response)
return false;
$response = json_decode($response);
if(!is_object($response))
return false;
if(isset($response->timezoneId) && !is_string($response->timezoneId)) // If google api, use timeZoneId
return false;
return $response->timezoneId;
}
Please Use this function
In case you find this thread, then take a look at timezoneapi.io.
With the address API you can request an address. The request returns:
The address
The timezone (and a lot of related information about the timezone)
The date / time about the timezone, e.g. what time is it in the timezone, is the timezone in DST, the currency, the capital etc.
In PHP
// Get JSON object
$jsondata = file_get_contents("https://timezoneapi.io/api/address/?Hacker+Way+1+Menlo+Park+California");
// Decode
$data = json_decode($jsondata, true);
// Request OK?
if($data['meta']['code'] == '200'){
// Example: Get the city parameter
echo "City: " . $data['data']['addresses']['0']['city'] . "<br>";
// Example: Get the users time
echo "Time: " . $data['data']['addresses']['0']['datetime']['date_time_txt'] . "<br>";
}
More documentation here:
https://timezoneapi.io/developers/address
I need to display user's activities date as per the current time zone.
My approach -
Getting a timezone offset from javascript and storing it to the user's profile table.
When user logged in, getting time zone offset.
current date is working fine with time zone offset-
$offsetDiff = $_SESSION['TimeZone']*60;
$UserDateTime = time() + $offsetDiff;
$currentDate = date('Y-m-d',$UserDateTime);
Dateo other then today is not working properly -
$offsetDiff = $_SESSION['TimeZone']*60;
$UserDateTime = '2014-02-10 08:58:00'; + $offsetDiff;
$monthUser = date('Y-m-d',$UserDateTime);
Can anybody please let me know how can i show correct date according to time zone offset?
You can convert a specific offset to a DateTimeZone:
$offset = '-0500';
$isDST = 1; // Daylight Saving 1 - on, 0 - off
$timezoneName = timezone_name_from_abbr('', intval($offset, 10) * 36, $isDST);
$timezone = new DateTimeZone($timezoneName);
Then you can use it in a DateTime constructor, e.g.
$datetime = new DateTime('2012-04-21 01:13:30', $timezone);
or with the setter:
$datetime->setTimezone($timezone);
In the latter case, if $datetime was constructed with a different timezone, the date/time will be converted to specified timezone.
I'm trying to get the user's timezone as a string on singup. example:
$timezone = "Asia/Tel_Aviv";
While researching the issue, I got how to Get timezone offset with Javascript, but I'm still unclear about how can I translate the timezone offset to a timezone string in php, as shown above?
Or, which other method cas I use in Javascript / PHP for getting the timezone string for each user?
I'm really not sure how to approach this.
You can't do this in PHP alone.
You can use Javascript to set the value in a cookie, then use PHP to read the cookie on the next page (re)load.
Javascript:
var dateVar = new Date()
var offset = dateVar.getTimezoneOffset();
document.cookie = "offset="+offset;
PHP:
echo $_COOKIE['offset'];
Use this to convert the offset to the friendly timezone name in PHP. Javascript returns the offset in minutes, while this PHP function expects the input to be in seconds - so multiply by 60. The third parameter is a boolean value of whether or not you are in Daylight Savings Time. Read the manual and update the code to fit your needs.
echo timezone_name_from_abbr("", intval($_COOKIE['offset'])*60, 0);
http://php.net/manual/en/function.timezone-name-from-abbr.php
You cannot get the timezone name from an offset. That's because there are many timezones which have the same offset at any given time, so you can't pick one based on an offset. (If you do, this will bite you in the butt later when the timezone goes into or out of DST, changing the offset.
Your best bet is to do geolocation by IP address (google it, lots of material out there) as a best first guess and then give the user an option to choose his timezone himself.
function tzone(){
if(isset($_SESSION["tz"])){ $return = $_SESSION["tz"]; } else {
$ip = $_SERVER["REMOTE_ADDR"];
$getip = file_get_contents("http://freegeoip.net/json/$ip");
$getip = json_decode($getip);
$lat = $getip->latitude; $lng = $getip->longitude; $country = $getip->country_name;
$getzone = file_get_contents("http://api.geonames.org/timezoneJSON?lat=$lat&lng=$lng&username=demo"); //you can change "demo" to your own username. its free service
$getzone = json_decode($getzone);
$zone = $getzone->timezoneId;
$_SESSION["tz"] = $zone;
$return = $_SESSION["tz"];
}
return $return;
}
You need to follow answers of Nicholas Pickering and deceze♦ partially. Do not use PHP's timezone_name_from_abbr function(Ref).
Follow these steps to get UTC time of any timezone set in user system:
Javascript (client-side):
var dateVar = new Date();
var offset = dateVar.getTimezoneOffset();
//getTimezoneOffset - returns the timezone difference between UTC and Local Time
document.cookie = "offset="+offset;
Php (server-side):
public function convert_utc_time($date)
{
$time_difference = isset($_COOKIE['offset'])?$_COOKIE['offset']:'';
if($time_difference != ''){
$time = strtotime($date);
$time = $time + ($time_difference*60); //minutes * 60 seconds
$date = date("Y-m-d H:i:s", $time);
} //on failure of js, default timezone is set as UTC below
return $date;
}
..
..
//in my function
$timezone = 'UTC';
$date = $this->convert_utc_time($post_date); //$post_date('Y-m-d H:i:s')
echo strtotime($date. ' '. $timezone)
Strangeness. It's not an edge case. Rather, let's say my server stores it's date/time in America/Toronto. I then run the it through time conversion logic incase, say, you're on the west coast. Here's the code I got:
$timestamp = '2012-07-25 16:30:00';
$to = 'America/Toronto';
$from = 'America/Toronto';
// system timezone
$system = (new DateTimeZone($from));
// desired conversion timezone
$desired = (new DateTimeZone($to));
// timestamp DateTime object
$resource = (new DateTime($timestamp, $system));
// offset
$offset = $desired->getOffset($resource);
print($offset);
The offset that is getting printed at this point is -14440 (4 hours). I don't imagine the system or database timezones are coming in here (both of which are set to America/Toronto). Any light would be appreciated on this. Confusing :(
DateTimeZone::getOffset() returns the offset in seconds from GMT (-14440 = 4 hours for America/Toronto).
Edit:
Apologies for my initial confusion with DateTime::getOffset()!
Anyway, to address the title of your question, use DateTime::setTimeZone() to convert between timezones.
This is probably what you're looking for, the offset between the 2 timezones.
// system timezone
$system = (new DateTimeZone($from));
// desired conversion timezone
$desired = (new DateTimeZone($to));
// timestamp DateTime object
$resource = (new DateTime($timestamp, $system));
$desiredDateTime = (new DateTime($timestamp, $desired));
// offset
$offset = $desired->getOffset($desiredDateTime) - $system->getOffset($resource);
print($offset);