How do I compare two datetime intervals in PHP? - php

I want to compare the interval of two datetimes to see if the interval is in the past, in the future or now.
$current_time = new DateTime();
$datetime1 = new DateTime('2018-03-17 18:25:00');
$datetime2 = new DateTime('2018-03-17 20:00:00');
if($current_time >= $datetime1 && $current_time <= $datetime2){
// now
} elseif($current_time >= $datetime1){
// past
} elseif($current_time <= $datetime1){
// future
}
EDIT:
Sorry, just realised posting my whole real code would make it easier for everyone.
The example above does work but it doesnt work when I loop thru the db using more than one interval from there
function interval(){
....
while($row = $result->fetch_assoc()){
$start_time = $row['start_time'];
$end_time = $row['end_time'];
$now = new DateTime();
$datetime1 = new DateTime($start_time);
$datetime2 = new DateTime($end_time);
if($now >= $datetime1 && $now <= $datetime2){
// now
}elseif($now < $datetime1 && $now < $datetime2){
// past
}elseif($now > $datetime1 && $now > $datetime2){
// future
}else{
// fail?
}
}
}

date returns a string. If you actually want to use a real DateTime object, then you need to do something like:
$now = new DateTime();
$other = new DateTime('2018-03-18 17:45:00'); //note: example made off the top of my head... value presented may not work
if ($now < $other) {
//do something
}
More information can, as always, be found in the PHP manual: https://secure.php.net/manual/en/class.datetime.php

As your dates are already string just compare them like that
$current_time = date("Y-m-d H:i:s");
$datetime1 = '2018-03-17 18:25:00';
$datetime2 = '2018-03-17 20:00:00';
if($current_time >= $datetime1 && $current_time <= $datetime2){
// now
} elseif($current_time >= $datetime1){
// past
} elseif($current_time <= $datetime1){
// future
}

Can you expand why your code isn't working as intended?
Below is how I would approach the question.
date_default_timezone_set('UTC');
$current_time = new DateTime();
$compareWith = new DateTime('2018-03-16 18:25:00');
if ($current_time >= $compareWith) {
//whatever your heart desires
}
else{
//whatever your heart desires
}

Related

How can I check if a given date is newer than 3 days?

I have a date
2016-09-16
How can I check that if that date is less than 3 days old?
I'm being really stupid and the frustration is making me not figure it out
Here's my code
public function isNew()
{
return strtotime($this->created_at) > time() && strtotime($this->created_at) < strtotime('+3 days',time());
}
Should be easy to use DateTime and DateInterval to handle this.
$date = new DateTime('2016-09-16');
$diff = (new DateTime)->diff($date)->days;
return $diff < 3;
Using PHP's DateTime and DateInterval Classes would do you much good. Here's how:
<?php
function isNewerThan3Days($date) {
$today = new DateTime();
$date = new DateTime($date);
$diff = $today->diff($date);
$diffD = $diff->days;
if($diffD>=3){
return false;
}
return true;
}
var_dump(isNewerThan3Days("2016-09-14")); //<== YIELDS:: boolean true
Use diff(). It will return a DateInterval object. Within that object will be a days property (days) that you can access.
// compare two distinct dates:
$datetime1 = new DateTime('2016-09-16');
$datetime2 = new DateTime('2016-09-12');
$interval = $datetime1->diff($datetime2);
$daysOld = $interval->days;
// int(4)
// or compare today vs your date...
$datetime1 = new DateTime('2016-09-16');
$now = new DateTime();
$interval = $now->diff($datetime1);
$daysOld = $interval->days;
// int(0)
// then determine if it's at least 3 days old:
$is3daysOld = ($daysOld >= 3 ? true : false);
http://php.net/manual/en/datetime.diff.php
This should do it for you.
$date = new DateTime('2015-09-16');
$now = new DateTime();
$interval = $date->diff($now);
$difference = $interval->format('%a');
if($difference < 3) {
// $date is fewer than 3 days ago
}
In your isNew() method:
public function isNew() {
$created_at = new DateTime($this->created_at);
$now = new DateTime();
$interval = $created_at->diff($now);
$difference = $interval->format('%a');
if($difference < 3) {
return true;
}
return false;
}
return $this->created_at->diffInDays() < 3;
Without parameter diffInDays() will return the number of complete days between created_at and now.
Why don't you use Carbon ?
You can easily do that and many more in carbon like so :
$dt = Carbon::createFromDate(2011, 8, 1);
echo $dt->subDays(5)->diffForHumans(); // 5 days before

PHP calculate between two time with H:i:s format

i'm trying to find and calculate between startime, finish time as: starttime + 1 hour and current time. if current time is between start and finish i must be print message such as please try after 1 hour:
$current_date_time = new DateTime("now", new DateTimeZone("Asia/Tehran"));
$user_current_time = $current_date_time->format("H:i:s");
$start_limit_time = date("H:i:s",strtotime('2015-09-15 14:57:31'));
$finish_limit_time = date('H:i:s', strtotime($start_limit_time) + (60 * 60 * 1));
$date1 = DateTime::createFromFormat('H:i:s', $user_current_time);
$date2 = DateTime::createFromFormat('H:i:s', $start_limit_time);
$date3 = DateTime::createFromFormat('H:i:s', $finish_limit_time);
if ($date1 > $date2 && $date1 < $date3)
{
echo 'here';
}
this code is not correct and i can not fix that,
You can try this, it shows the difference in minutes:
$current_date_time = new DateTime("now", new DateTimeZone("Asia/Tehran"));
$user_current_time = $current_date_time->format("H:i:s");
$start_limit_time = date("H:i:s",strtotime('2015-09-15 14:57:31'));
$finish_limit_time = date('H:i:s', strtotime($start_limit_time) + (60 * 60 * 1));
$date1 = DateTime::createFromFormat('H:i:s', $user_current_time);
$date2 = DateTime::createFromFormat('H:i:s', $start_limit_time);
$date3 = DateTime::createFromFormat('H:i:s', $finish_limit_time);
if ($date1 > $date2 && $date1 < $date3)
{
$tryAgainIn = $date3->diff( $date1 );
// just minutes
echo "try again in ".$tryAgainIn->format( "%i minutes" );
// or hours and minutes
$hours = $tryAgainIn->format('%h');
$minutes = $tryAgainIn->format('%i');
echo "try again in $hours hours and $minutes minutes";
}
For more information take a look at: DateTime::diff
At first you should avoid operating with strings format, as they should only be used IMHO to printing and retrieving data from outside. Use only timestamp or OOP methods.
I believe, that this is something you are looking for:
$startTime = new DateTime('2015-09-15 14:57:31');
$endTime = clone $startTime;
$endTime->modify('+1 hour');
if ($startTime->getTimestamp() <= time() && time() < $endTime->getTimestamp()) {
echo 'here';
}
I wonder why you need to use H:i:s format. Can you give some bigger picture?
Edit: Try this, as prior to now I did not fully understand what you want to do ;)
$origin = new DateTime('2015-09-15 14:57:31');
$startTime = new DateTime('today '.$origin->format('H:i:s'));
$endTime = clone $startTime;
$endTime->modify('+1 hour');
if ($startTime->getTimestamp() <= time() && time() < $endTime->getTimestamp()) {
echo 'here';
}

PHP check if today is in between two dates

Consider following code:
$today = date("d/m/Y");
$start_date = '20/11/2014';
$time1 = strtotime($start_date1);
$start_date1 = date('d/m/Y',$time1);
$end_date = '20/01/2015';
$time2 = strtotime($end_date1);
$end_date1 = date('d/m/Y',$time2);
if( $start_date1 <= $today && $end_date1 >= $today)
echo "yes";
else
echo 'no';
Even though $today is in between those start and end date, I get "no" in return. What might be the problem here? I just wanna check if today is in between those dates. Start date and end date are saved as string in DB.
Try this:
<?php
$now = new DateTime();
$startdate = new DateTime("2014-11-20");
$enddate = new DateTime("2015-01-20");
if($startdate <= $now && $now <= $enddate) {
echo "Yes";
}else{
echo "No";
}
?>

How to add & compare two times using php

I want to compare two times.
But first i would like to count up one time for 110 minutes.
What did i do wrong?
Code:
$current_time = date("H:i");
$match_start = strtotime("H:i", "19:30"); // <- Value from database
$match_end = strtotime("+110 minutes", $match_start)
if($current_time > $match_start && $current_time < $match_end) {
//Match has started
}
Another solution using strtotime()
$current_time = strtotime(date("H:i")); // or strtotime(now);
$match_start = strtotime("14:30");
$match_end = strtotime("+110 minutes", $match_start);
if($current_time > $match_start && $current_time < $match_end) {
echo "Match has started";
}
Working demo
It might have to do with the fact that you are comparing strings, not actual time values. Try using DateTime() which makes this clearer.
$current_time = new DateTime();
$match_start = new DateTime("19:30");
$match_end = (new DateTime("19:30"))->modify("+110 minutes");
if($current_time > $match_start && $current_time < $match_end) {
//Match has started
}
First, create datetime like this (change your datetimezone):
$match_start = "19:30"; // <- Value from database
$current_time = new DateTime('', new DateTimeZone('Europe/Rome'));
$start = new DateTime($match_start, new DateTimeZone('Europe/Rome'));
$end = new DateTime($match_start, new DateTimeZone('Europe/Rome'));
Then add 110 minutes to end time:
$end->add(new DateInterval('PT110M'));
Finally:
if($current_time > $start && $current_time < $end)
{
//Match has started
}

PHP checking if two dates differs at least three months

In php how to check if one date (given as string) differs to another date at least three month (unable to find any examples):
$date1 = "2013-11-05";
$date2 = "2013-11-19";
//both dates is in form yyyy.mm.dd
differsThreeMonths($date1,$date2) { ???? return $differs; }
differsThreeMonths("2013-11-05","2014-05-02");//true
differsThreeMonths("2014-01-01","2014-04-01");//true
differsThreeMonths("2014-01-01","2014-03-31");//false
differsThreeMonths("2013-12-01","2014-01-15");//false
etc
Thank you
$datetime1 = new DateTime('2013-07-01 12:00:00');
$datetime2 = new DateTime('2013-11-11 12:00:00');
$interval = $datetime1->diff($datetime2);
if(($interval->m>=3) || ($interval->y > 0))
echo "at least 3 months";
else
echo "Not greater than 3 months";
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
var_dump($interaval);
http://www.php.net/manual/en/datetime.diff.php
Try:
function differsThreeMonths($date_str1, $date_str2) {
if (strlen($date_str1) > 0 && strlen($date_str2) > 0) {
$date1 = new DateTime($date_str1);
$date2 = new DateTime($date_str2);
$since_start = $date1->diff($date2);
return (($since_start->y > 0) || ($since_start->m >= 3));
} else {
return -1; // ERROR CODE HERE
}
}

Categories