Getting the wrong timezone when outputting user registration date in Wordpress - php

I'm trying to output user registration time in the local timezone, but Wordpress stores the user_registeredvalue in UTC format. Backend settings are set to be +2h.
The following code:
$user_registered = $user_info->user_registered;
will display the UTC time like 2018-10-25 15:04:45, where I need it to be 2018-10-25 17:04:45
I tried to get the local time of user registration with get_gmt_from_date function like this
$formatted_time = get_gmt_from_date( $user_registered, $format = 'H:i:s');
but that is not working. How do I output local time format for user registration time?

That's good. You want everything stored in UTC.
Just create a DateTime object, then set the appropriate time zone. As an example:
<?php
$x = new DateTime('2018-10-25 15:04:45', new DateTimeZone('UTC'));
echo $x->format('Y-m-d H:i:s')."\n";
$x->setTimeZone(new DateTimeZone('Europe/Brussels'));
echo $x->format('Y-m-d H:i:s')."\n";
Which will output:
2018-10-25 15:04:45
2018-10-25 17:04:45
See it here: https://3v4l.org/OF8Ff

Related

Get accurate date and time from the server ( Prevent local time )

I've been trying to get time from the server using different methods like Date.Now() and Carbon::now() but the problem with this approach is the visitor is easily able to change his/her computer time and the return response from the server will change according to the visitor time on the computer.
Here's what i am actually trying to do
I have 6 different questions in the database that i would like to show on different days.
For example: On 20 November, 2019 i would like to show the Question #1 and on 24 November, 2019 i would like to show the Question #2
The problem here is, If the visitor changes his date to 24 November, He will be able to see the question in advance whereas i only want them to know this question on the date i specified in the system.
This is how i am sending a response back to my AJAX call.
public function getSer(Request $request)
{
$now = new DateTime('now',new DateTimezone('America/New_York'));
return response()->json($now);
}
The returned time is based on the local client time and not the server.
I've also tried the following:
$question = Questions::where('question_start', '<=', Carbon::now('America/New_York'))->where('question_end', '>=', Carbon::now('America/New_York'))->first();
dd($question);
But the results are changing as i change date on my operating system
The solution is simple:
Perform the date/time check on the server and render the question
Something like this:
<?php
$question_one_start = DateTime::createFromFormat('Y-m-d H:i:s','2019-11-20 00:00:00',new DateTimezone('America/New_York'));
$question_one_end = clone $question_one_start;
$question_one_end->modify('+1 day');
$now = new DateTime('now',new DateTimezone('America/New_York'));
if($now >= $question_one_start && $now < $question_one_end){
echo "Question output here.";
}
else if( ... ) {
....
}
With this you don't need to perform any kind of date/time check on the client.
Date/time presentation is a client/UI issue. The client should take the time that the server returned (whether it is in UTC or not), and convert it to the client's local time zone.
EDIT due to updated question: I still don't see the issue. The server is responsible for fetching questions up to (I assume) the current date. It doesn't matter what the client's date/time is. The server will still only fetch and return questions for the current date. If the client changes their date to the year 2100, that doesn't impact the query that the server is doing.
Perhaps the problem is that you are letting the client specify the date/time query range, instead of the server?

Is there any way user can set timezone from (database) their profile setting in codeigniter?

I am working on user setting page where some of the default settings for the user are like user default timezone, user date format, user time format.
I am able to store user-specific setting in my database and get them. but when the user changes his timezone it's set properly but it does not show date according to latest timezone.
For example, user current timezone is 'Asia/Kolkata' and when he update timezone to any other timezone like 'America/New_York' the details get saved in the database and it also shows current timezone 'America/New_York' but it does not reflect 'America/New_York' date and time. its shows 'Asia/Kolkata' time only. When I re-login the same user its shows correct time as per last updated timezone.
I have already tried below code
$utc_time = $dateinfo; // date from database
$timezone = $ci->session->userdata('user_settings')->TIME_ZONE; // user last updated timezone
$date_obj = new DateTime($utc_time, new DateTimeZone($ci->session->userdata('user_settings')->TIME_ZONE));
$date_obj->setTimeZone(new DateTimeZone($timezone));
$display_date = $date_obj->format(get_datetimeformat() . '(e)');
return $display_date; // show date based on updated timezone
I am expecting to show date and time based on selected timezone without re-login.
If anyone can help me in the right direction, it will very helpful.
Thanks,
In your Controller do this
$user_timezone = 'Asia/Tokyo'; //make sure you get this data from your user
date_default_timezone_set($user_timezone); //set it as default according to their time zone.
echo $user_timezone. "<br>";
echo date('Y-m-d');
echo "<br>The time is " . date("h:i:sa");
Let me know the result.
Hope that helps :)
Thanks for all response. I have solved the issue.
I have converted all date() function to gmdate() in my application so now all date and time get store in UTC in my database.
I did some changes in my helper function as below, and its working like charm for me.
$date_obj = new DateTime($utc_time, new DateTimeZone('UTC'));
Thanks!!!

local time format in php

I tried to post the StartRecordDateTime and EndRecordDateTime to a api.
2018-07-11T11:00:00Z is the utc time format. I wonder what is the format for local time melboune australia.
e.g. "2018-07-11T11:00:00 Australia/Melbourne" this will give me an error. Obviously, it depends on the api.
My qeustion is that do we have format like 2018-07-11T11:00:00Z with the Z at the end to indicate time zone for local time?
{
"RecordDuration": "600000",
"StartRecordDateTime": "2018-07-11T11:00:00Z",
"EndRecordDateTime": "2018-07-11T11:10:00Z"
}
You can create a function and insert these codes:
$melbourne = new DateTimeZone('Australia/Melbourne');
$melbourneDT = new DateTime('your date time', $melbourne);

PHP Timezone adjust as per user

Im creating a UI where users get to choose their timezone. My backend is PHP and I know you can do it a few ways but I had questions about all of them and which way is the best:
http://ca2.php.net/date_default_timezone_set
//where America/Los_Angeles will be changed based on user
date_default_timezone_set('America/Los_Angeles');
Does this change the server timezone for ever user or just what is being exported? is there any performance issues with this?
What if it was a function like this...?
date_default_timezone_set('America/Los_Angeles'); -08:00 set in php.ini
$date = "2014-01-01 12:00:00";
$new_time_zone = "America/New_York" // -05:00 = +3 hours difference
function adjust_time_zone($string, $zone){
$datetime = new DateTime($string);
$new_zone = new DateTimeZone($zone);
$datetime->setTimezone($new_zone);
return ($datetime->format('Y-m-d H:i:s'));
}
adjust_time_zone($date, $new_time_zone);
Results(i tested this):
2014-01-01 15:00:00 //3 hours ahead.
in this format everything stamped in the system would be on LA time and exported would be the change...
I know there is allot of these Timezone threads but there seems to be allot of "i do it like this" and not any solid "this way blows my socks off="
Thanks for any help you can give!
I store everything in the db as a datetime and UTC timezone.
I store the user's timezone in the db ($timezone).
So when a time ($time) is taken from the db, I run it through the following function:
function changetimefromUTC($time, $timezone) {
$changetime = new DateTime($time, new DateTimeZone('UTC'));
$changetime->setTimezone(new DateTimeZone($timezone));
return $changetime->format('m/d/y h:i a');
}
This returns the time in the user's timezone, formatted.
edit: you can see the db table of timezones in this thread:
Generating a drop down list of timezones with PHP
Well it looks like what you have should work for you. This is an alternate method, although not necessarily better. You can just use PHP's mktime and pass the hour offset to it.
<?php
print "<br>Date: ".date("Y-m-d H:i:s");
// DEFINE AN OFFSET
$offset = -5; // TIMEZONE OFFSET: '-5' FOR NEW YORK
// ADD THE OFFSET TO THE CURRENT TIME
print "<br>Date Offset: ".$date_offset = date("Y-m-d H:i:s", mktime(date("H") + $offset, date("i"), date("s"), date("m"), date("d"), date("Y")));
I found a great solution to the problem - and to adapt the date and time settings on my page according to the users settings.
Ready build js code
Some developers that had the exact same problem build a javascript solution to the code. You don't need to know javascript as long as you follow these instructions.
Go to https://bitbucket.org/pellepim/jstimezonedetect/src/default/
Read through the readme file if you want to
Either download the script as an NPM package or download it manually by pressing "downloads" in the left menu.
If you pressed downloads to manually download the script press "Download repository" to get the files.
Create a js folder - named "js" in your project. (optional)
Unzip the jstimezonedetect files into the js folder. I chose to name the unziped file "jstimezonedetect".
To reach the files above my current directory is /js/jstimezonedetect/.
In your header code (important it is in header since the time-zone will affect the full code on the rest of your page unless you run a function.
Enter the following code to your php file:
echo '
<script src="js/jstimezonedetect/dist/jstz.min.js"></script>
<script>
document.cookie = "usertimezone="+jstz.determine().name();
</script>
';
$settimezone = $_COOKIE['usertimezone'];
date_default_timezone_set($settimezone);
The first line of script will import the jstz.min.js file from the importat jstimezonedetect project.
Second line will create a cookie (you can later delete the cookie if you want to).
In the third line I get the cookie into the php script and then I use PHP date_default_timezone_set();
(https://www.php.net/manual/en/function.date-default-timezone-set.php)
to set the timezone.
Worked perfectly for me. :) Ask if something is unclear.

users to view in local timezone

I've asked a very similar question before but got no answers that helped.
I have a site that allows users to post notes. There will be a time stamp on those notes. The default timezone on my server is EST5EDT (despite me setting the date.timezone to something else, which is a different issue!).
As far as I can gather, it is best to set the timestamp with the server time and convert it for each user. For example:
User 1 (GMT) posts "Hello World" at (local time) 5:00 (server time) 0:00
User 2 (AEST, +10) sees that User 1 posted "Hello World" at (local time) 15:00
For the sake of argument, I am avoiding worrying about DST as I don't think it counts for this.
I understand I can use date_default_timezone_set() within my application but I am quite sure I should set the post time as the server time so no need to change the set timezone.
I only want to convert the time for the viewer
"Post as Server Time, Read as Local Time"
I do not believe I am the first person who has had their web app perform this so there must be an answer out there.
I will have to get the datetime the post was made, get the timezone of the user viewing the post (probably through javascript as php uses server side date and time) and convert the datetime using the user's timezone.
getTimezoneOffset() in javascript will work out the users time difference from UTC but not from my server time.
What you can do is save the UTC time when saving and when viewing show the UTC time + offset.
This can all be done using JS on client side.
JS method used when saving= UTC()
JS method used when displaying =
<html>
<head>
<script type="text/javascript">
function showDateInClientSideFormat(dValue)
{
var d = new Date()
var n = d.getTimezoneOffset();
var dateClientSide = new Date(dValue +n);
return dateClientSide;
}
</script>
</head>
<body>
<?php
echo '<script> showDateInClientSideFormat($dateSaved); </script>';
?>
</body>
</html>
PS: UTC time is the same as GMT time
You could use PHPs DateTime and DateTimeZone to convert the datetime into the users current timezone:
http://www.php.net/manual/de/class.datetime.php
http://www.php.net/manual/de/class.datetimezone.php
$date = new DateTime($dateTimeFromDB);
$date->setTimeZone( new DateTimeZone('User/Timezone') );
echo $date->format('d.m.Y H:i');

Categories