PHP compare time with undefined Timezones - php

I need to compare times, I am using variables to define timezones, the current time and the time to be compared.
I am using this script to do certain actions based on what the user selects. The user can select a time when this action should be done, a date and a timezone.
If the current time is > or equal than the time selected by the user those action should run.
So I need to compare the current time and the time selected by the user. The current time is given by the timezone selected by the user.
This is the code I have. The comparison is not working fine. It thinks the oppposite thing than what should actually thinks... I need an help.. possibly not using php 5.3 or above. Better if functions are avaialbe from version 4 to 5
date_default_timezone_set($TimeZone); //all the possible php timezones available can be choosen by the user
$todaydate = date('Y-m-d');
$time_now=mktime(date('G'),date('i'),date('s'));
$NowisTime=date('G:i:s',$time_now); //the time given by the selected timezone above
$time = $ris['Time']; //the time defined by the user in the DB
if($NowisTime >= $time){
DO THE ACTIONS
}else{
exit;
}

If user defined time in database is relative to same timezone. you could try this snippet follow:
$dateTimeZone = new DateTimeZone("Asia/Chongqing");
$localTime = new DateTime("now", $dateTimeZone);
$definedTime = new DateTime("2011-05-29 10:00:00", $dateTimeZone);
if ($localTime >= $definedTime) {
echo "It is about time.";
} else {
// do nothing.
}
It would be better to save user defined time with Unix Time Stamp.

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!!!

Getting the wrong timezone when outputting user registration date in Wordpress

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

Limit the access of a function to once every 24 hours PHP + MySQL

I would like to limit the access of a function i've created to once every 24 hour based on the users IP address. I would also like the PHP script to delete the MySQL record if it's older than 24 hours.
If the user already has used the function within 24 hours, show them a message and prevent the script from continue running.
If the user already has used the function but 24 hours has passed since he used the function, delete the MySQL record and let the script continue running.
I'm lost and as you can see i am also missing some statements for deleting old records (-24 hours)..
Could anyone provide me with an example of how to do this? Thanks
Get client's IP address and store it with current date and time if the record doesn't exist.
Fetch the record and add 24 hours to its date and time value and check it with the current date and time every time the script is executed.
You need if else conditional statements to check if the 24 hours time is over or not. Based on that, you will control the execution of the function you want to.
I think I don't want to write much of theory. Here, I've written the pattern what the code looks like:
if(!$record_in_db) {
// create record with the client's ip address and the current date and time
// invoke the function you want - This is the code to trigger the function first time for the new IP address
} else {
// fetch_record_from_db
// add 24 hours to its date and time value
// check it with current date and time
$record_date_time = new DateTime('22-12-2016 22:45:20'); // this value should be fetched from database
$record_date_time_by_24_hours = $record_date_time->modify('+1 day');
$current_date_time = new DateTime(date('d-m-Y H:i:s', strtotime('now')));
$date_time_diff = $current_date_time->diff($record_date_time_by_24_hours);
if($date_time_diff->invert == 0) {
// Do something
} else {
// update the date and time of the record to NOW which is current date and time
// invoke the function you want
}
}
I can't write you the whole code. I could only give you some hints. You need to build the code from it. Hope I've given you right hints that could help you.

Timezones and email cron job: how to do it right?

I've searched around in SO and elsewhere but have not found a direct answer to this, so at this point I believe it merits an entry here. Please advise if you think otherwise.
I am using Codeigniter 2.0.2, PHP 5.2.14, MySQL 5.0.77.
I am setting up a cron job that will run every 15 minutes. This cron job will run a model script that checks DB for events requiring an email alert. Events that return true are cue'd up for sending emails.
My issue is with the timezones of my users. My server is EST (UTC -5). If I have a user that registered as UTC +5, my script will send the email alert 10 hours earlier than expected.
To remedy this, I wanted to ask if this workflow is acceptable:
user is UTC +5
server is UTC -5
scheduled event is 10PM (21:00) at user's local time
subtract the timezone difference (21:00 - 10 = 11AM)
send email out at 11AM
Some of the answers I found are here
How to schedule emails to send out
Generating a schedule that works over different timezones and DSTs
but I wonder if someone could provide a better roadmap/schema to set up my script.
Any pointers are much appreciated, also re how to account for daylight saving time both local and from the user.
Thanks.
As suggested already I would normalise all dates being written into your database into UTC and then you can read them out of there easily, converting back as you read them if necessary.
The CONVERT_TZ() function will let you easily perform these conversions. eg.
CONVERT_TZ('2011-05-11 15:23:00','GMT','Europe/London');
I use this function to convert timezones:
function switch_timezone($format, $time = null,
$to = "America/Los_Angeles", $from = "America/Los_Angeles")
{
if ($time == null) $time = time();
$from_tz = new DateTimeZone($from);
$to_tz = new DateTimeZone($to);
if (is_int($time)) $time = '#' . $time;
$dt = date_create($time, $from_tz);
if ($dt)
{
$dt->setTimezone($to_tz);
return $dt->format($format);
}
return date($format, $time);
}
Seems like you should be able to use it to convert your current time into the right database time for SELECTs and vice versa.

Categories