Add time to datetime and check in if statement - php

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.";
}
?>

Related

How can I get the duration beetwen an empty date timestamp and an other determined?

I am coding to calculate a duration between an empty timestamp date and an other, non-empty, Please help me.
I would like to calculate this duration to set a confirmation's code expires when a participant in the forum comes back too late or doesn't come back over 2 days as a maximum delay
This code works fine except when the come back date is empty:
$date_participation= strtotime($row['date_participation']);
$date_come_back= strtotime($row['date_come_back']);
$expiration_delay = 2;
$days = $expiration_delay * 86400;
echo "<br> duration in seconds is: " . $date_come_back-
$date_participation;
if (($date_come_back- $date_participation) >= $days){
$sql_set_expired = "UPDATE `winners` SET `confirmation_status` = 'expired' WHERE id_recharge_winner ='$i'";
$set_expired_result = mysqli_query($conn, $sql_set_expired);
}
the `$i` is the participant's row in table winners
This is how I result my problem whiout worry if there is an Empty date:
I maked my one fuction
Difference_between_timestampdate()
than I specify one day like an expiration duration. It works fine, Thanks to those who helped me.
function Difference_between_timestampdate($first_date, $last_date){
$first_date = strtotime($first_date );
$last_date = strtotime($last_date);
$days = $expiration_delay * 82800;
if(empty($last_date)){
$duration = time() - $first_date;
}else{
$duration = $last_date - $first_date;
}
return $duration;
}
$date_participation = $row['date_participation'];
$date_come_back = $row['date_come_back'];
$expiration_delay = 1; //One day
if ((Difference_between_timestampdate($date_participation, $date_come_back)/82800 )
>= $expiration_delay){echo 'Expired duration';}else{echo 'Valid duration';}

Check if date() is greater than a specific time

In my code I pretty much send a token to the database with the
date('Y-m-d H:i:s');
function. But I am checking to see if the timestamp I sent if greater than 60 seconds if so i echo yes and else no. I keep getting no and I know its more than a minute because i time it. I've seen post about this but they're using specific dates and I am just going on when a user submits a form and checking if the token is 60 seconds old. Here is my code
php
<?php
require_once('db_login.php');
$stmtToken = $handler->prepare("SELECT * FROM email_token");
$stmtToken->execute();
$rowToken = $stmtToken->fetch();
$date = $rowToken['time_stamp'];
if($date > time() + 60) {
echo 'yes';
} else {
echo 'no';
}
?>
You can also play with dates in different manners. All four lines here are equivalent:
$now = (new \DateTime(date('Y-m-d H:i:s')))->getTimestamp();
$now = (new \DateTime('now'))->getTimestamp();
$now = (new \DateTime())->getTimestamp();
$now = time();
And then you can compare in this manner:
$tokenExpirationTimestamp = (new \DateTime($date))
->modify('+60 seconds')
->getTimestamp();
$isTokenExpired = $tokenExpirationTimestamp < time();
if ($isTokenExpired) {
// ...
}
When you compare times and dates you can either use datetime or strtotime.
Using strings will not work as expected in all cases.
In comments you mentioned how you want to compare, and you need to add the 60 seconds to the "date", not the time().
if(strtotime($date) + 60 < time()) {

PHP remove the New text after 1 day

I would add the New text if one day is not passed but if it is passed i would delete the text New if one day is passed.
I tried this code :
<?php
$farkZaman = time() - strtotime("2017-09-26 19:00:00");
$farkGun = floor($farkZaman / (60 * 60 * 24));
if($farkGun < 1){
echo "Yeni";
}
?>
How can i do ?
I need your help.
Note : I have French but i don't have a good English.
Don't know if this is what you are looking for.
Here is set $dt as tomorrow with a time (about 24 hours from now GMT+1).
Then I compare if time is less than this time.
If it is I echo the text.
$dt = strtotime("2017-09-29 06:40");
If(time()<=$dt){
Echo "the text";
}
You can do something like this.
if(strtotime($date_variable) > strtotime("-1 day")) {
echo "New";
}
Try like this
<?php
$now = new DateTime();
$now->format('Y-m-d H:i:s');
$created_date = new DateTime(date('Y-m-d', strtotime("2017-09-27 13:00:00")));
$day = $created_date->diff($now)->days; // 0
if($day < 1){
echo "new texts";
}
?>

how to check if time is more than 30minute?

I have saved a time. I would like to check whether the saved time is 30 minutes greater than the current time. You can see in the code what I have done so far but it doesn't work.
I would need some help fixing that code.
$current = "08:05";
$to_check = date('h:i');
if($to_check > $current + strtotime('30 minute')){
echo "greater";
}
else {
echo "not greater";
}
First, your $current isn't the current time, $to_check is, so your variable names are misleading.
That being said, store your "08:05" as a Unix timestamp then see if the difference between the two is greater than 30 * 60.
$seconds = 1800; // 30 mins
$time1 = strtotime($db_time) + $seconds;
if(time() >= $time1)
echo "Time's up!"
else
echo "time has not expired";
This should work for you:
<?php
$current = date('H:i');
$to_check = date('H:i', strtotime('+30 minutes'));
$to_check = date('H:i', strtotime($record['date'])); //If value is from DB
if($to_check > $current){
echo "greater";
}
else {
echo "not greater";
}
Save time using time function this would give you time in seconds from 1970 so for example current time is 1501137539 and after 30 minutes it would be (1501137539 + 30*60) so you would just need to check if difference b/w current time and stored time is greater that 30*60 then half an hour is over.
Try this snippet:
function x_seconds($to_check = 'YYYY-mm-dd H:i:s') {
$to_check = strtotime($to_check);
$current = time() + 1800; //We add 1800 seconds because it equals to 30 minutes
return ($current>=$to_check) ? true : false;
}
Or go pro, and have a custom "seconds since", just because you can?
function x_seconds($to_check = 'YYYY-mm-dd H:i:s', $seconds = 1800) {
$to_check = strtotime($to_check);
$current = time() + $seconds; //We add x seconds
return ($current>=$to_check) ? true : false;
}
Example usage:
$date = date('Y-m-d H:i:s', '2017-07-27 05:00');
if(x_seconds($date)):
print "Is within 30 minutes.";
else:
print "IS NOT within 30 minutes";
endif;
Try this to solve the issue
$current = strtotime('12:00:00');
$to_check = strtotime(date('H:i:s'));
$newtime = round(( $to_check - $current ) /60 );
if($newtime > 30){
echo "greater";
}else {
echo "not greater";
}

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'));

Categories