$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
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 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.
thanks for reading.
Just need to know how i convert datetime gotten from my sql tables in gmtime to datetime in user timezone.
the following is my code but doesn't seem to work..
//WHERE $post_arr[5] is date from sql
$user_date=convert_date_for_user($post_arr[5]);
function convert_date_for_user($date_time){
$user = JFactory::getUser();
$db = JFactory::getDBO();
$timezone=$user->getParam('timezone');
echo $tz_offset;
$user_date = JFactory::getDate($date_time,$timezone);
$user_date_str = $user_date->toUnix(true);
return $user_date_str;
}
It converts but I'm getting all the wrong time from the above code.
The simplest way to do it:
$useUserTimeZone = true;
JHtml::date($sqlGmtTimestamp , 'D F n, Y', $useUserTimeZone);
$sqlGmtTimestamp takes GMT timestamp/datetime
$useUserTimeZone is a flag to use user's timezone, otherwise server's timezone will be used.
more details here: http://docs.joomla.org/API16:JHtml/date
You don't specify your Joomla version but, did you try Joomla's JDate class directly?
// Get the User and their timezone
$user = JFactory::getUser();
$timeZone = $user->getParam('timezone', 'UTC');
// Create JDate object set to now in the users timezone.
$myDate = JDate::getInstance('now', $timeZone);
// Gets the date as UNIX time stamp.
$myDate->toUnix():
// For your example using a method
function convert_date_for_user($date_time)
{
// Get the User and their timezone
$user = JFactory::getUser();
$timeZone = $user->getParam('timezone', 'UTC');
// Create JDate object set to now in the users timezone.
$myDate = JDate::getInstance($date_time, $timeZone);
return $myDate->toUnix();
}
This is the function that works for me:-
//WHERE date_time is the format of the date taken directly from database(ie: 0000-00-00 00:00:00)
function convert_time_zone($date_time){
$user =& JFactory::getUser();
$db = JFactory::getDBO();
$timezone=$user->getParam('timezone','UTC');
$time_object = new DateTime($date_time, new DateTimeZone('UTC'));
$time_object->setTimezone(new DateTimeZone($timezone));
$user_datetime=$time_object->format('Y-m-d H:i:s');
//SELECT ONLY 1 line below
return $user_datetime; //WOULD RETURN DATETIME IN 0000-00-00 00:00:00
//OR
return $time_object->getTimestamp(); //WOULD RETURN DATETIME IN UNIX TIMESTAMP
}
Its a little out of the way as i was hoping to use functions included in the joomla API to do it. If anyone could provide a better solution please do. and i select it as the right answer.
With Joomla 2.5+ (i think), you can use the following code
echo JHtml::_('date', $input, $format, $tz, $gregorian);
$input can be one of the following values:
"now" for the current time (DEFAULT)
A date/time string in a format accepted by date()
$format can be one of the following values:
NULL to use the default locale based format (DEFAULT)
A date format specification string (see http://php.net/manual/en/function.date.php)
$tz can be one of the following values:
TRUE to use the user's time zone (DEFAULT). Note: If the user's time zone is not set then the global config time zone is used.
FALSE to use global config time zone
NULL for no conversion
A timezone string (eg: "America/Los_Angeles", see http://php.net/manual/en/timezones.php)
$gregorian can be one of the following values:
TRUE to use Gregorian calendar
FALSE to NOT use Gregorian calendar (DEFAULT)
Having tried all the given possible solutions here and not getting the date in the user's timezone (Joomla! v.3.9.14), here's my (proven) solution:
$oUser_TZ = JFactory::getUser()->getTimezone();
$aUser_tz = (array)$oUser_TZ; // almost sure this step is not that necessary
$full_date = JFactory::getDate('now', $aUser_tz['timezone']); // pretty sure $oUser_tz->timezone will work
// I had try to use $full_date->Format('Y-m-d H:i:s') but it was giving me the non-converted-to-wanted-timezone date, so
$date_converted = substr($full_date, 0, 19);
date_converted gives me the date in format Y-m-d H:i:s and in the wanted timezone.
Try This:
$date = JFactory::getDate(); // now - 2014-03-11 08:45:22
$date->setOffset(8); // UTC+8
echo $date->toMySQL(); // wrong - 2014-03-11 08:45:22
echo '<br />';
echo $date->toFormat(); // right - 2014-03-11 16:45:22
JHtml::date($post_arr[5]);
If you want a different format, use the second parameter:
JHtml::date($post_arr[5], DateTime::RFC2822);
Which is equivalent to:
1. Create a JDate object with an UTC date read from the database
2. Get the correct Time Zone in Jomla Global Configuration and User Configuration
3. Call setTimeZone() to convert your JDate object to user local time
4. Call format() to format the JDate object as a well formatted string
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)
im writing a twitter web service in php. When a user signs in, i receive this node:
<utc_offset>-18000</utc_offset>
I have to change the script's timezone so that it adapts to the user's real timezone. The only php function i have found for this is: date_default_timezone_set($timezone_identifier) but it won't let me use -18000 as a the $timezone_identifier parameter.
So, how can i change the current user timezone based on two values: Server UTC offset and User UTC offset
BTW, this is how i'm getting the server UTC offset value:
$this_tz_str = date_default_timezone_get();
$this_tz = new DateTimeZone($this_tz_str);
$now = new DateTime("now", $this_tz);
$offset = $this_tz->getOffset($now);
Any ideas? Thanks!
To get current server time
date_default_timezone_set(date_default_timezone_get());
echo date('Y-m-d H:i:s', time());
Output for Europe/Paris (my server settings; UTC+2)
2011-04-12 20:39:43
To get user's time by offset
$user_offset = '-18000';
date_default_timezone_set('UTC');
$diff = "$user_offset seconds";
if ((substr($diff,0,1) != '+') && (substr($diff,0,1) != '-')) $diff = '+' . $diff;
$usertime = strtotime($diff, time());
echo date('Y-m-d H:i:s', $usertime);
Output UTC-5 (Ecuador -> Quito time NO DST), php timezone identifier 'America/Guayaquil'.
2011-04-12 13:39:43
PHP.net manual:
Timezone offset in seconds. The offset
for timezones west of UTC is always
negative, and for those east of UTC is
always positive. (-43200 through
50400)
The date_default_timezone... functions expect a string giving something like "Africa/Luanda" or whatever.
I suggest programmatically searching through the timezone database for a matching offset. If I recall correctly, those are in minutes from UTC, so you should divide the offset you are given by 60.