Selecting upcoming sessions based on UNIX timestamps - php

I have a service that shows a specific button when a session is "ready", i.e. 15 minutes beforehand and through the session.
I am doing this by pulling up all recently requested sessions, analyzing their timestamps, and then pulling out a specific ID if that session is upcoming. Here is the code:
$session_check_query = "SELECT * FROM requested_sessions WHERE username_t = '{$_SESSION['username']}'";
$session_check_process = mysql_query($session_check_query);
date_default_timezone_set($_SESSION['timezone']);
$current_time = time();
while ($sessions = mysql_fetch_array($session_check_process)) {
if ($sessions['time_from_t'] - $current_time <= 900 && $current_time - $sessions['time_from_t'] > 0 && $sessions['accepted'] == 1) {
$session_id = $sessions['id'];
}
}
The problem is that when I echo $session_id in the loop it will output 1, 2, 3, 4. This means that it feels that all of my sessions in the database meet this criteria when they don't only one does.
Is there a problem with this code? time_from_t is in UNIX format.

One possible problem may arise from the fact that time() is timezone independent - it always returns the UTC time (this fact is buried in the comments). More robust handling of timezones can be handled with the DateTime object:
$date = new DateTime('now', new DateTimeZone($_SESSION['timezone']));
$current_time = $date->format("U");
Either way, the next step would be to verify your $current_time variable and the time_from_t to see where the maths is going wrong.

Related

PHP Operators for Greater/Less than BOTH triggered on same numbers

Trying to add a simple X minute timer to an order status. I'm doing this by setting the timezone, loading the current UNIX time into a variable, then adding X minutes for a trigger time. Every time the page loads, it checks the stored "trigger" time and compares it to the current time. If the current timestamp is larger than the stored one, move on to the next step. The next step happens regardless of the "now" being less than "overtime".
$now = (int) time(); //1550450927
$overtime = strtotime(+5 minutes); //1550451222
//also tried datetime format
$now = new DateTime('now');
$overtime = $now->modify('+10 Minutes');
if ( $now >= $overtime ) { //if "overtime" has passed
//stuff happens with no regard for reality
//driving me absolutely bonkers
}
Checking the database inputs of current times compared to requested times, everything is correct with the numbers. They are being stored exactly as the examples given, UNIX timestamps.
Calling modify() is updating the $now value as well as the $overtime value.
Also, this may be of interest to you How do I deep copy a DateTime object?
Try:
$now = (int) time(); //1550450927
$overtime = strtotime("+5 minutes"); //1550451222
//also tried datetime format
$now = new DateTime('now');
$overtime = (new DateTime("now"))->modify("+5 minutes");
print_r($now);
print_r($overtime);
if ( $now >= $overtime ) { //if "overtime" has passed
echo "hit";
//stuff happens with no regard for reality
//driving me absolutely bonkers
}

PHP - Time based math

How exactly is this done? There's so many questions on stack-overflow about what I'm trying to do; However all of the solutions are to edit the MYSQL Query, and I need to do this from within PHP.
I read about the strtotime('-30 days') method on another question and tried it, but I can't get any results. Here's what I'm trying:
$current_date = date_create();
$current_date->format('U');
... mysql code ...
$transaction_date = date_create($affiliate['Date']);
$transaction_date->format('U');
if($transaction_date > ($current_date - strtotime('-30 days'))) {
} else if(($transaction_date < (($current_date) - (strtotime('-30 days'))))
&& ($transaction_date > (($current_date) - (strtotime('-60 days'))))) {
}
Effectively, I'm trying to sort all of the data in the database based on a date, and if the database entry was posted within the last 30 days, I want to perform a function, then I want to see if the database entry is older than 30 days, but not older than 60 days, and perform more actions.
This epoch math is really weird, you'd think that getting the epoch of the current time, the epoch of the data entry, and the epoch of 30 and 60 days ago would be good enough to do what I wanted, but for some reason it's not working, everything is returning as being less than 30 days old, even if I set the date in the database to last year.
No need to convert to unix timestamp, you can already compare DateTime objects:
$current_date = data_create();
$before_30_day_date = date_create('-30 day');
$before_60_day_date = date_create('-60 day');
$transaction_date = date_create($affiliate['Date']);
if ($transaction_date > $before_30_day_date) {
# transation date is between -30 day and future
} elseif ($transaction_date < $before_30_day_date && $transaction_date > $before_60_day_date) {
# transation date is between -60 day and -30 day
}
This creates (inefficiently, see my comment above) an object:
$current_date = date_create(date("Y-m-d H:i:s"));
From which you try to subtract an integer:
if($transaction_date > ($current_date - strtotime('-30 days'))) {
which is basically
if (object > (object - integer))
which makes no sense.
you're mixing the oldschool time() system, which deals purely with unix timestamps, and the newer DateTime object system, which deals with objects.
What you should have is
$current_date = date_create(); // "now"
$d30 = new DateInterval('P30D'); // 30 days interval
$transaction_date = date_create($affiliate['Date']);
if ($transaction_date > ($current_date->sub($d30)) { ... }
You might consider DatePeriod class, which in essence gives you the ability to deal with a seires of DateTime objects at specified intervals.
$current_date = new DateTime();
$negative_thirty_days = new DateInterval::createFromDateString('-30 day');
$date_periods = new DatePeriod($current_date, $negative_thrity_days, 3);
$thirty_days_ago = $date_periods[1];
$sixty_day_ago = $date_periods[2];
Here you would use $thirty_days_ago, $sixty_days_ago, etc. for your comparisons.
Just showing this as alternative to other options (which will work) as this is more scalable if you need to work with a larger number of interval periods.

Getting and Storing a timestamp difference using PHP and MySQL

I'm creating a basic game for a final project; the entire site is built and ready to go, but I can't get one functionality working.
The function is that over time the user's pet's stats will lower.
The longer you are away from your pet the lower their stats get until they "die". So far I'm trying to calculate the time difference between the logins by using this code:
$mod = mysqli_query($con,"select * from users where user_name='$user_name'");
while($row = mysqli_fetch_array($mod)){
$last_login = $row['last_login'];
$stored_login = $row['stored_login'];
$time_diff = ($last_login-$stored_login);
echo $time_diff;
$time_mod = mysqli_query($con,"update users set time_mod='$time_diff' where user_name='$user_name'");
}
Both the last_login and stored_login are TIMESTAMP variables, and I've been told I should be able to subtract them easily to get a solution.
However, when I echo the equation all it returns is 0. I've tried using DATEDIFF but MySQL gives me an error saying I can't use it. I only need the number of days that have passed - Is there any way to make this happen?
If it helps, you can access the beta here (either create an account or you can log on with):
http://www.eurogabby.com/MyPetMonster/login.php
username: a
password: a
Maybe you can try. Convert to time the row.
$last_login = strtotime($row['last_login']);
$stored_login = strtotime($row['stored_login']);
$time_diff = ($last_login - $stored_login);
echo $time_diff;
you just need to convert the time using strtotime like this
$time_diff = (strtotime($last_login)-strtotime($stored_login));
echo $time_diff;
if this not works then first convert them to strtotime and store in different variables then subtract them like
$last = strtotime($last_login);
$stored = strtotime($stored_login);
$time_diff = ($last-$stored);
echo $time_diff;
Now you can convert back to time using date function like this
$newtime = date("m/d/Y",$time_diff);
echo $newtime = month/day/year
remember m/d/y will be your choice of date format in which you want to convert.

PHP MYSQL compare time with created in database

I want to check if 30 min passed after created time in database. created is a time column having time stamp in this format 1374766406
I have tried to check with date('m-d-y H:i, $created) but than of course it is giving human readable output so don't know how to perform check if current time is not reached to 30min of created time.
Something like if(created > 30){}
Try this:
$created = // get value of column by mysql and save it here.
if ($created >= strtotime("-30 minutes")) {
// its over 30 minutes old
}
The better approach is to use DateTime for (PHP 5 >= 5.3.0)
$datenow = new DateTime();
$datenow->getTimestamp();
$datedb = new DateTime();
$datedb->setTimestamp(1374766406);
$interval = $datenow->diff($datedb);
$minutes = $interval->format('%i');
$minutes will give you the difference in minutes, check here for more
http://in3.php.net/manual/en/datetime.diff.php
Here is the working code
http://phpfiddle.org/main/code/jxv-eyg
You need to use strtotime(); to convert the date in human form back to a timestamp, then you can compare.
EDIT: Maybe I misread.
So something like;
if(($epoch_from_db - time()) >= 1800){
//do something
}

Subtract php format date and set the difference value in a textbox [duplicate]

How can I compute time difference in PHP?
example: 2:00 and 3:30.
I want to convert the time to seconds then subtract them then convert it back to hours and minutes to know the difference. Is there an easier way to get the difference?
Look at the PHP DateTime object.
$dateA = new DateTime('2:00');
$dateB = new DateTime('3:00');
$difference = $dateA->diff($dateB);
(assuming you have >= PHP 5.3)
You can also do it the procedural way...
$dateA = strtotime('2:00');
$dateB = strtotime('3:00');
$difference = $dateB - $dateA;
See it on CodePad.org.
You can get the hour offset like so...
$hours = $difference / 3600;
If you are dealing with times that fall between a 24 hour period (0:00 - 23:59), you could also do...
$hours = (int) date('g', $difference);
Though that is probably too inflexible to be worth implementing.
Check this link ...
http://www.onlineconversion.com/days_between_advanced.htm
I used this to calculate the difference between server time and the users local time. Grab the hour difference and drop that in a form when the user is registering. I then use it to update the time on the site for the user when they do stuff online.
Once I got it working, I switched this line ...
if (form.date1.value == "")
form.date1.value = s;
to ...
form.date1.value = "<?PHP echo date("m/d/Y H:i:s", time()) ?>";
Now I can compare the user time and the server time! You can grab the seconds and mins as well.

Categories