Timestamp older than current time if else statement - php

Im testing an online/offline function with timestamp from the database against DateTime NOW.
But I cant figure out how to set interval time on lets say 5 minutes.
If the user has not done anything in 5 minutes, appear offline.
DateTime NOW will always be bigger than Database time.
Any ideas on how to set the interval time on the statement ?
This is what i have so far,
// $user_info['activity'] 2013-04-27 19:27:39 //
$dateTime = new DateTime("now", new DateTimeZone('Europe/Warsaw'));
if($user_info['activity']>$dateTime){
echo 'user Online';
}else{
echo 'user inactive';
}

Something liKe this might work
$now = new DateTime(null, new DateTimeZone('Europe/Warsaw'));
$last_activity = new DateTime($user_info['activity']);
$last_activity->modify('+5 minutes');
if($now > $last_activity){
echo 'user inactive';
}else{
echo 'user online';
}

Use DateTime::diff() for this:
$now = new DateTime();
$activity = $user_info['activity'];
// get difference between the two dates
$difference = $now->diff($activity);
// ->i contains the minutes
if($difference->i >= 5) {
echo "logged out";
}

One possible solution is to change your database timestamp to be a DateTime object as well and then use the DateTime::diff() method for comparison.
$dateTime1 = new DateTime(strtotime($user_info['activity']), new DateTimeZone('Europe/Warsaw'));
$dateTime2 = new DateTime("now", new DateTimeZone('Europe/Warsaw'));
$interval = $dateTime1->diff($dateTime2);
This will allow you to determine the interval and do a comparison using it.

I did this recently, like this:
$time = time();
$last_activity = //time from db
$time_since = $time - $last_activity
Then clean up $time_since if necessary for your application.

Related

check if new DateTime is today or future in php

I need to check if date1 is today or future date and if so its ok
if not (is in the past) its not ok. i see a lot of examples but none of theme is check if date1 is equal today.
my code is:
$today = new DateTime(); // Today
$today->format('Y-m-d'); //2016-10-27
$contractDateBegin = new DateTime($date1); //2016-10-27
if($today->getTimestamp() <= $contractDateBegin->getTimestamp()){
echo 'OK';
}
else{
echo "NOT OK";
}
its work fine if date1 is a future date but if its the same date its echo "NOT OK"
any help?
$today can be defined as just new DateTime("today"), which means today at midnight -- the time part will be automatically zeroed out
$today = new DateTime("today");
$date1 = '2016-10-27';
$contractDateBegin = new DateTime($date1); //2016-10-27
if($today <= $contractDateBegin){
echo 'OK';
}
else{
echo "NOT OK";
}
DEMO
The "Y-m-d format" is perfect also for direct lexicographical comparison of strings and there is no need to convert it to a DateTime object. With PHP7 you could use the famous speceship operator ;)
php -a
Interactive mode enabled
php > $today = '2016-10-27';
php > $tomorrow = '2016-10-28';
php > $today2 = '2016-10-27';
php > echo $today <=> $tomorrow;
-1
php > echo $today <=> $today2;
0
php > echo $tomorrow <=> $today2;
1
getTimestamp() included "H:i:s". So it'll fail when compare the seconds.
In your case, do you want to compare just date('Y-m-d')?
If you just want to use DateTime and compare Timestamp. Please try
$today = new DateTime(); // Today
$contractDateBegin = new DateTime($date1); //2016-10-27
// Set time to 0
$today->setTime(0, 0, 0);
$contractDateBegin->setTime(0, 0, 0);
if($today->getTimestamp() <= $contractDateBegin->getTimestamp()){
echo 'OK';
}
else{
echo "NOT OK";
}
I guess you only want to compare the dates (ignoring the time). This should work:
$today = new DateTime();
$today = $today->format('Y-m-d');
$contractDateBegin = new DateTime($date1);
$contractDateBegin = $contractDateBegin->format('Y-m-d');
if ($today <= $contractDateBegin){
echo 'OK';
} else {
echo "NOT OK";
}

How to calculate time difference?

i have 2 type of time values are 2015-09-25 11:52:22 and 2015-09-25 01:06:57. i using date different function in php. my code as
$date_a = new DateTime($from_time);
$date_b = new DateTime($to_time);
$interval = date_diff($date_a,$date_b);
echo $interval->format('%h:%i:%s');
Out put gives 10:45:25.how can calculated time diff??
2015-09-25 11:52:22 is AM and 2015-09-25 01:06:57 is PM that time only i got look like otherwise coming correct
The 'diff' method applies to a DateTime Object..
$from_time = '2015-09-25 11:52:22';
$to_time = '2015-09-25 01:06:57';
$date_a = new DateTime($from_time);
$date_b = new DateTime($to_time);
//$interval = date_diff($date_a,$date_b);
$interval = $date_a->diff($date_b);
echo $interval->format('%h:%i:%s');
// 10:45:25

Simulate "do not disturb" functionality in PHP

I want to check between two user-specified times everyday and not run some function call (i.e. "Do Not Disturb").
For example, a user set a "Do Not Disturb" time block between 10:00pm to 6:00am (next day).
FYI, no days/dates are being specified by the end-user, ONLY times. This will run consistently everyday, 7 days a week.
So between 10pm-6am (next day), any function call is ignored. This is what I've written up so far:
$now = time(); // or $now = strtotime('11:00pm'); to simulate time to test
$start = strtotime('10:00pm');
$end = strtotime('6:00am +1 day');
// alternative time block
//$start = strtotime('10:00am');
//$end = strtotime('11:00am');
//debug
//echo date('r', $now) . '<br>' . date('r', $start) . '<br>' . date('r', $end) . '<br><br>';
if($start > $now || $now > $end) {
echo 'disturb';
} else {
echo 'do not disturb';
}
But this doesn't seem to work, because once you reach midnight, it's a new day, but the $end variable is already a day ahead.
I tried putting it a day behind, but then the issue is that the value of $end ends up being lower than the value of $start, which isn't correct.
I also tried adding a day to the $now variable whenever the time reaches midnight, but the issue w/ that is, what if the $start and $end times are within the same day?
What am I missing here?
Apparently you're trying to build some kind of calendar functionality here.
If you use strtotime('10:00pm'); this will change to the timestamp of the next day after midnight.
So you need to give the variable a date
$start = strtotime('2015-02-26 10:00pm');
$end = strtotime('2015-02-27 6:00am');
Not sure how you store these time blocks, but ideally they would be stored in a database table.
If it's every day the same you could do:
$now = time(); // or $now = strtotime('11:00pm'); to simulate time to test
$start = strtotime('10:00pm');
$end = strtotime('6:00am'); // without the +1 day
if($start > $end) {
if($start > $now && $now > $end) {
echo 'disturb';
} else {
echo 'do not disturb';
}
}else{
if($now < $start || $now > $end) {
echo 'disturb';
} else {
echo 'do not disturb';
}
}
That's a nice question actually,
You can use the the relatively new object oriented way of dealing with times.
I'll link you some info as I don't have time to write an entire example
http://php.net/manual/en/datetime.diff.php
http://php.net/manual/en/class.datetime.php
http://php.net/manual/en/class.dateinterval.php
specifically from the docs :
<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>
Hope it helps
I would convert to DateTime() objects instead. Then you won't get any issues with days ending.
// obviously you'll need to feed in the date as well so
// that might involve some refactoring
$now = new DateTime();
$start = new DateTime('2015-02-26 10:00');
$end = new DateTime('2015-02-27 06:00');
Now you can compare as before.
If you don't know the date and your users are only specifying time, you might need to add the date dynamically. These are just for example.
Edit: to cope with unknown days, you could dynamically generate after grabbing today:
$today = new DateTime();
$start = new DateTime($today->format('Y-m-d') . ' 10:00');
$end = new DateTime($today->format('Y-m-d') . ' 06:00');
$end->add(new DateInterval('P1D'));

Add time to datetime and check in if statement

I am stuck. I have a database with colummn datetime in comments table. Basicly when user adds a new comment it's inserted in this table and the datetime is stored. So what i want to do now is to check if, lets say 1 minute is passed since he last commented. But i am getting all the time true in if statement.
Well. Before posted this did the last check. Output is not as expected.
My code.
$limits = new Limits();
$user = new User();
$time = new DateTime();
$time->add(new DateInterval('PT' . 1 . 'M'));
$stamp = $time->format('Y-m-d H:i:s');
$limit = $limits->check_comment_limit($user->loggedInUser());
if($limit->time < $stamp){
echo 'Take a brake';
}
//for debugging
echo $stamp . '<br>';//2014-03-18 13:38:41
echo $limit->time; //2014-03-18 01:37:37
Ok obviusly $limit->time is smaler than $stamp. With time() it's simple, time() + 60 but how to do this with datetime?
I think this is that you want to do:
<?php
date_default_timezone_set('UTC');
// Get current datetime.
$now = new DateTime("now");
// Get last comment datetime.
$comment = new DateTime('2014-03-18 13:26:00');
// Get interval limit between comments.
$limit = new DateInterval('PT1M');
// Calculate the difference between the current and last commented datetime.
$diff = $now->diff($comment);
// Calculate the total minutes.
$minutes = $diff->days * 24 * 60;
$minutes += $diff->h * 60;
$minutes += $diff->i;
// Debug output
echo $now->format('Y-m-d H:i:s').'<br>';
echo $comment->format('Y-m-d H:i:s').'<br>';
echo $limit->i.'<br>';
echo $minutes.' minutes <br>';
// Limit smaller than difference? Next comment is allowed.
if($limit->i <= $minutes) {
echo "Your comment has been saved!";
} else {
echo "Your aren't allowed to comment now. Wait ".intval($limit->i*60 -
$diff->format('%s'))." seconds until you are allowed to comment again.";
}
?>
Edit: Added missing calculation of total minutes. Otherwise the calculation don't work with dates with the same minutes but other day or hour.
Another and much simpler/generic (working with every interval) solution would be like this:
<?php
date_default_timezone_set('UTC');
// Get current datetime.
$now = new DateTime("now");
// Get last comment datetime.
$comment = new DateTime('2014-03-18 16:45:00');
// Get and add interval limit to comments.
$limit = new DateInterval('PT1M');
$comment->add($limit);
// Debug output
echo $now->format('Y-m-d H:i:s').'<br>';
echo $comment->format('Y-m-d H:i:s').'<br>';
// Limit smaller than difference? Next comment is allowed.
if($comment <= $now) {
echo "Your comment has been saved!";
} else {
echo "Your aren't allowed to comment now. On ".$comment->format('Y-m-d H:i:s')." you
are allowed to comment again.";
}
?>

Getting date/time difference in PHP

Am trying to get the time difference between two days. But for certain date/time, I get wrong answers
Here is my code:
/****************************************
$start_date = new DateTime('23:58:40'); *These two still give
$end_date = new DateTime('00:00:00'); *a wrong answer
*****************************************/
$start_date = new DateTime('23:58:40');
$end_date = new DateTime('00:11:36');
$dd = date_diff($end_date, $start_date);
//Giving a wrong answer: Hours = 23, Minutes = 47, Seconds = 4
echo "Hours = $dd->h, Minutes = $dd->i, Seconds = $dd->s";
The awnser is correct. You provide two times. Without a date there is no way to know the last date is actually the next day. Just because you named the variable "end_date" doesnt mean PHP knows what you mean.
Perhaps you should include the date aswell in your request like
$start_date = new DateTime('2012-12-07 23:58:40');
$end_date = new DateTime('2012-12-08 00:11:36');
If you realy want to work with just times:
function differenceInTimes($start, $end) {
if (strtotime($start)>strtotime($end)) {
//start date is later then end date
//end date is next day
$s = new DateTime('2000-01-01 '.$start);
$e = new DateTime('2000-01-02 '.$end);
} else {
//start date is earlier then end date
//same day
$s = new DateTime('2000-01-01 '.$start);
$e = new DateTime('2000-01-01 '.$end);
}
return date_diff($s, $e);
}
$start_date = '23:58:40';
$end_date = '00:11:36';
$dd = differenceInTimes($start_date, $end_date);
echo "Hours = $dd->h, Minutes = $dd->i, Seconds = $dd->s";
//Hours = 0, Minutes = 12, Seconds = 56
Swap the arguments to date_diff
$dd = date_diff($start_date, $end_date);
Edit
After actually testing this theory it proved to be totally useless, giving the same answer.

Categories