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
Related
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)
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);
I need a method that gets two strings that represents a DateTime (in the MySql syntax) and returns the time difference between them.
Then I need to compare that time to 3 seconds so I could block a Brute Force attack on my server.
I've messed a lot with Google and I managed to get the string representation of the DateTime object, but I can't manage to convert and compare them.
$time_str1 = '2011-09-10 19:59:23'; // first string datetime from DB
$time_str2 = '2011-09-10 19:59:24'; // second string datetime from DB
// first DateTime object created based on the MySQL datetime format
$dt1 = DateTime::createFromFormat('Y-m-d H:i:s', $time_str1);
// second DateTime object created based on the MySQL datetime format
$dt2 = DateTime::createFromFormat('Y-m-d H:i:s', $time_str2);
// difference comparison to check if at least 3 seconds have passed
if ( ($dt2->format('U') - $dt1->format('U')) > 3) {
echo 'Ok, no brute force'; // yes, three seconds have passed
} else{
echo 'We got you newbie'; // nope, three second haven't passed
}
$diffInSeconds = $dateTimeLater->format('U') - $dateTimeFirst->format('U');
strtotime( $timeStr ) which will convert to the amount of seconds since epoch http://en.wikipedia.org/wiki/Unix_epoch . Then you can just use standard mathematical operators. Be warned, strtotime can be inaccurate sometimes. To convert back, date("m-d-Y H:i:s", $time)
Heres an alternative method using a session, no need to query a db for a timestamp:
<?php
session_start();
function post_check($limit){
//Check for first time
if(isset($_SESSION['post_check'])){
//Check for count on failed
if(isset($_SESSION['post_check_count'])){
//If fail count is more then 3 block till user closes down browser
if($_SESSION['post_check_count']>$limit){
die('Too many requsets to the server, please close down your browesr and try again.');
}
}else{
//Set for count on failed
$_SESSION['post_check_count']=0;
}
//Check (time-limit) against timestamp held in session
if(($_SESSION['post_check']+$limit)<=time()){
//Update timestamp
$_SESSION['post_check']=time();
//Ok
return true;
}else{
//Update Fail count
$_SESSION['post_check_count']++;
//Fail
return false;
}
}else{
//Set for first time
$_SESSION['post_check']=time();
return true;
}
}
//Pretty self explanitry here
if(post_check('3')===true){
echo 'Allowed: handle post stuff here';
}else{
echo'Too many requests within given time limit do nothing';
}
?>
On the MySQL side:
SELECT UNIX_TIMESTAMP(my_time) FROM my_table
On the PHP side, you then have UNIX timestamps in seconds, which you can compare.
Edit: This function does work in PHP, it isn't working for me within the CakePHP framework which I didn't think relevant when originally posting.
This function takes a string formatted date/time and a local timezone (e.g. 'America/New_York'). It supposed to return time converted to the local timezone. Currently, it does not change.
I pass it: '2011-01-16 04:57:00', 'America/New_York' and I get back the same time I pass in.
function getLocalfromGMT($datetime_gmt, $local_timezone){
$ts_gmt = strtotime($datetime_gmt.' GMT');
$tz = getenv('TZ');
// next two lines seem to do no conversion
putenv("TZ=$local_timezone");
$ret = date('Y-m-j H:i:s',$ts_gmt);
putenv("TZ=$tz");
return $ret;
}
I've seen the references to the new methods for default_timezone_get/set. I'm not currently interested in using that method because I'd like this code to work with older versions of PHP.
Apparently, in CakePHP, if you're using date_default_timezone_set() in your config file, which we are, the TZ environment variable setting method does not work. So, the new version, which seems to work perfectly is:
function __getTimezone(){
if(function_exists('date_default_timezone_get')){
return date_default_timezone_get();
}else{
return getenv('TZ');
}
}
function __setTimezone($tz){
if(function_exists('date_default_timezone_set')){
date_default_timezone_set($tz);
}else{
putenv('TZ='.$tz);
}
}
// pass datetime_utc in a standard format that strtotime() will accept
// pass local_timezone as a string like "America/New_York"
// Local time is returned in YYYY-MM-DD HH:MM:SS format
function getLocalfromUTC($datetime_utc, $local_timezone){
$ts_utc = strtotime($datetime_utc.' GMT');
$tz = $this->__getTimezone();
$this->__setTimezone($local_timezone);
$ret = date('Y-m-j H:i:s',$ts_utc);
$this->__setTimezone($tz);
return $ret;
}
how about this
<?php
// I am using the convention (assumption) of "07/04/2004 14:45"
$processdate = "07/04/2004 14:45";
// gmttolocal is a function
// i am passing it 2 parameters:
// 1)the date in the above format and
// 2)time difference as a number; -5 in our case (GMT to CDT)
echo gmttolocal($processdate,-5);
function gmttolocal($mydate,$mydifference)
{
// trying to seperate date and time
$datetime = explode(" ",$mydate);
// trying to seperate different elements in a date
$dateexplode = explode("/",$datetime[0]);
// trying to seperate different elements in time
$timeexplode = explode(":",$datetime[1]);
// getting the unix datetime stamp
$unixdatetime = mktime($timeexplode[0]+$mydifference,$timeexplode[1],0,$dateexplode[0],$dateexplode[1],$dateexplode[2]);
// return the local date
return date("m/d/Y H:i",$unixdatetime));
}
?>