PHP check if 5min + of time and date - php

I'm working on a chat / activity system. My site currently logs all activity being page, button submission and if a message is sent its added to a table called activity. With a time stamp and date in format: 12:44:06 (time) 2016-10-19 (date)
I need to check if there is no activity for a user after 5 minutes.
Therefore I can determine if the user is online or not online. Each activity row has a u_id (user id)
I would prefer it was PHP based. I just need a basic php function. So I have $time $date and to check if 5 minuets has passed from that set $time $date value

If you're using OOP php, you could do that this way:
$last = DateTime::createFromFormat('Y-m-d H:i:s', $yourDate.' '.$yourTime);
$now = new Datetime('now');
$minutes = abs( $last->getTimestamp() - $now->getTimestamp() ) / 60;
Then check if it's bigger than 5 and do stuff.
You can also install Carbon, which is an extension of the DateTime class and it makes your life easier when handling dates in php.
Check here: http://carbon.nesbot.com/
Then you could do it this way:
$then = Carbon::createFromFormat('Y-m-d H:i:s', $yourDate.' '.$yourTime);
if($then->addMinutes(5)->isPast()) {
// stuff
}
Way cleaner.

You can do it using mysql like below:
SELECT TIMESTAMPDIFF(MINUTE, datatime_col, now())
With above query you will get the difference in minutes, which you can compare as it is greater than 5 minutes or not.

Related

Php/MySQL Adding time from a form to current date then inserting into DB

I've been looking everywhere for information on how to add an amount of time (months) specified in a form on a Php website to current date, and then adding this date into MySQL database Date (for ex. 2014-03-03) field (if using Date is even possible here).
Could You tell me what should I use to take the current date without time, add a custom amount of months to it (using strtotime I assume, but it uses syntax like +1 days, where I have a variable from a form), and then input it into database field type "Date"? I could change the DB field type to Datetime or Timestamp if needed.
You can use mktime for this:
<?php
print date("Y-m-d", mktime(0, 0, 0, date("m") + 6, date("d"), date("Y")));
Here, I have added 6 months to the date.
following this logic it should be pretty easy to save your date in mysql. =)
strtotime is a great function because its always very easy to understand what's going on at a glance.
$days = $_POST['days']; // data from your form
$currentTime = strtotime('today'); // you can also use time() or put in your own date
$nextDay = strtotime('+'.$days.' days', $currentTime); // add number of days from form
$nextDay = date('Y-m-d H:i:s', $currentTime); // format the time from unix timestamp into mysql format

Updating 'Date' Data based on Current Date

Let's say I have a table and it consists a column of next_update (which is in a date format), time_left (which is in the unit of days). How could I program it for example the next_update is 27/02/14 and the time_left is 3 days for today(24/02/14) view in a php webpage but for tomorrow view in the php page will be automatically deducted to 2 days. I'm using postgresql as my database and php as the web interface. The main problem now is how can I make the value of time_left be minus by the next_update with the current date.
I've gone through some basic manual but still have no idea to set this up. Sincerely thank you all for any help.
Try this code
<?php
$now = time();
$next_update = strtotime("2014-02-27");
$datedifferent = $next_update - $now;
$days = floor($datedifferent/(60*60*24));
if($days > 0) {
echo $days.' more days you have';
}
?>
SELECT next_update, next_update - now() as time_left FROM <your_table>
You may also want to apply function EXTRACT to subtract necessary time units from interval (documentation)

PHP server side timeout check

Is there a simple straight forward way to find the remaining time between a start date - ex: 2013-01-10 12:34:55 and 5 minutes later?
What I mean is I have the start date and want to check that 5 or 60 minutes later gives a time difference of 0. Kind of a time out to be checked on server side.
You have 2 dates, correct ?
$date1 = strtotime('2013-01-10 12:34:33'); // converto to time
$date2 = strtotime('2013-01-10 12:45:33'); // or else it won't work
$diff = date('u', $date1) - date('u', $date2); // the difference in seconds between the two
// if you want $date2 to be now, just use date('u')
if ($diff > 3600) { // an hour later
echo 'The difference between $date1 and $date2 is more than an hour';
}
If you want to do something like "session time out" for the user. Use Javascript setintervel() and do ajax() call to logout user from the application.
Well, seems like I was going the harder way... found that it would be easier and more reliable to get it from an sql check than in php.
I've implemented this with success. Leave it here just in case it might be useful.
$query = "SELECT * FROM db_table
WHERE DATE_ADD(my_start_date, INTERVAL 5 MINUTE) > NOW()";
Where 5 is the interval that can be set in seconds (SECOND), minutes (MINUTE), hours (HOUR), days (DAY) etc.

advice with php date and timestamps

We have a battle system where people can pick a match time to challenge another player. To create a match the user needs to pick a date. Currently a user picks the day, hour, minute, and pm/am from a dropdown list. If the user selects 5/20/2012 # 1PM, the system adds the hours and minutes from the start of the day. Here's a quick sample to get a better understanding of what I'm talking about:
$time = strtotime('today', $inputdate);
$time = $time + $hours + $minutes;
the value of $hours changes if the users selects AM or PM. It's pretty basic:
Everything was working fine until people started have timezone issues. For example, if player A creates a match at 1:PM, then player B will see the match starts at 1:PM, but he/she will have different timezones!
The problem is that I don't know the problem :/
I don't know how to fix the timezone issue. I have been creating functions in the hopes that everything will fall together, but no luck.
What I have:
User profiles have a timezone options.
A function that gets the raw timestamp and returns the formatted time based on the user's timezone.
A function that gets a timestamp and converts it to another timestamp
based on the user's timezone.
I'm lost and I can't seem to fix the issue, I can code, but right now I'm not thinking logical. I took me one hour to write this and try to explain it how I could, since I myself don't know how to make it work. Some advice is appreciated.
I need a function to convert a timestamp to UTC-5:
function input_date($timestamp)
{
global $vbulletin;
$timestamp = (int)$timestamp;
if (strlen((string)$timestamp) == 10)
{
$hour = 3600.00;
$offset = $vbulletin->userinfo['timezoneoffset'];//sample -8
$ds = (int)$vbulletin->userinfo['dstonoff'];//DST
$fluff = $hour*($offset+5.00);
$timestamp = $timestamp+$fluff+($ds*$hour);
return $timestamp;//return timestamp in UTC-5 format..
}
else
{
return 0;
}
}
Essentially everything in the database should be stored using a single timezone, preferably one which is not affected by DST. The standard option here is UTC.
If you know the user's timezone by its name, you can use that to generate your time:
// Player A creates match at 1PM Europe/London
$timezone = 'Europe/London';
$localTime = '2012-03-01 13:00:00';
// work out UNIX timestamp using that timezone (making it timezone independent)
date_default_timezone_set($timezone);
$timestamp = strtotime($localTime);
// store $timestamp in the database
// Player B views the timestamp with timezone America/Los_Angeles
$timezone = 'America/Los_Angeles';
date_default_timezone_set($timezone);
var_dump(date('c', $timestamp)); // see manual for more output formats
If you have the timezones stored as their abbreviations (e.g. "CET", "GMT"), then use timezone_name_from_abbr to get the correct timezone name.

MySQL datetime and Current Date Time function

I'm a novice to php's date() and strtotime, and have been attempting to find out the solution to this for the great portion of the day with no real solution (I've come close, but to no avail).
What I have is a typical database row with a 'submitted' column, which is entered via a submitted=NOW() (in datetime format). I'm attempting to get the current datetime and find the difference between both values in "x Hours and x minutes". To make matters a little more interesting my web server is an hour behind me in terms of timezones. I've tried the "date_default_timezone_set('EST');" and it does help doing the straight date() function but obviously doesn't help me with my already inserted datetimes.
$lastEntryDate = date('l, F dS Y', strtotime($entryDate));
$lastEntryTime = date('g:ia', strtotime($entryDate.'+1 hour'));
$currDate = date('l, F dS Y');
$currTime = date('g:ia');
So, tried doing $lastEntryTime - $currTime, but that obviously gets messed up depending on the time of day (as it's in 24 hour format, I believe).
I've googled around and found a couple of posts on forums indicating using the 3600 (seconds in an hour), and I'm still trying to wrap my head around this.
Is there something basic I'm missing? Or is this quite complex as I think it is?
$now = time();
$entrytime = strtotime($entryDate) + (60 * 60) //60 seconds times 60 minutes = 1 hour
$difference = $now - $entrytime;
$hours = floor($difference / (60 * 60));
$minutes = $difference - ($hours * 60 * 60);
a solution that may be helpful to you is instead of using the MySQL now function why not make your submitted field of the INT type and then store a unix timestamp in it using the php time() function, then before inserting that into the database just add 1 hour in seconds to the timestamp. Then when you retrieve the data from your table you should be able to work with the timestamp and the php date and time function to create whatever timestamp you want. Here is a link on the php time() function which may help:
http://php.net/manual/en/function.time.php

Categories