Check if difference between dates is greater than X minutes in PHP

Asked

Viewed 3,309 times

4

First of all, I’ve done a lot of research here on the site and I haven’t found any more in-depth examples, just basic questions/answers on how to get the difference between dates, what I was able to do and it works as I wish.

However, the code that I currently possess, seems to me a little "heavy" but as I do not have advanced knowledge in PHP, I do not know how could simplify.

I have a JSON file with some data, some of it needs to be updated when it is already 30 minutes since its creation. For this I use the following code to create the time used in the json file:

'time' => date('m/d/Y H:i:s')

When I do the date request, I then compare the date saved in the json file with the current date. If it is more than 30minutes, I have to do another treatment. This is the code I currently use:

$fileTime = new DateTime($file['time']); //Data obtida do arquivo json
$currTime = new DateTime();
$interval = date_diff($fileTime, $currTime);

if($interval->y >= 1 || $interval->m >= 1 || $interval->d >= 1 || $interval->h >= 1 || $interval->i >= 30) {
    //Chama função
}

The problem with that is that if it’s 1:10 minutes and I just check the minutes, it’s going to give a wrong result, since it’s been over 30 minutes, so I have to check every house after the minute too.

Is there any way to simplify this verification?

2 answers

4


I always try to give an alternative with the primitive functions of date, because they are usually very simple and instead of objects return numbers, which are naturally efficient for subsequent operations.

Instances and methods are good when abstraction brings gain and simplicity to non-critical operations in terms of time. As in the present case there is no gain with the abstraction of Datetime, we can simply do this:

$date1 = strtotime( '10/04/2016 15:00' );
$date2 = strtotime( '10/04/2016 16:10' );

If one of the dates is the current one, you can use this:

$date1 = time(); // use mktime() para hora local

To calculate the difference:

$intervalo = abs( $date2 - $date1 ) / 60;

if( $intervalo > 30 ) {
   // 
}

See the calculation on IDEONE.

Important note that when the date is separated by traces, PHP already interprets as DD-MM-AAAA, and with bars as MM/DD/AAAA. If you need it, you can change it like this:

strtotime(str_replace('/', '-', '11/04/2016 18:10'));

The value returned is in seconds, divided by 60 to calculate the minutes.

If you prefer, you can use this syntax if you are sure that the date 2 will always be greater than 1:

$intervalo = $date2 - $date1 / 60;

And obviously, it can absurdly simplify the code once you’ve understood the general idea:

$date1 = strtotime( '10/04/2016 15:00' );
$date2 = strtotime( '10/04/2016 16:10' );

if( $date2 - $date1 > 1800 ) {
   // 1800 segundos = 30 minutos
}

Note that if using timestamp or datetime in the database, in many Dbs like mysql, you can already get the values without using strtotime even (with unix_timestamp). Saves one more step in both data volume and data format processing.


If you need to display the value, or use current time, see this variant:

Convert date difference to string

  • Baco, I’m having a doubt, I’m doing with the following dates: $date1 = strtotime( '10/04/2016 15:00' ); $date2 = strtotime( '11/04/2016 18:10' ); and it’s showing me a difference of 747 hours, as is possible?

  • "When the date is separated by dashes, PHP already interprets as DD-MM-YYYY, and with bars as MM/DD/YYYY"

  • In other words, if this 11 is to be the day, use the format "11-04-2016". If you use bar, it is in the American standard

  • And as I would with bars, to change the form to day-month-year?

  • Only switch to dash when calling strftime

  • Thank you, Bacco!

  • @Gonçalo http://ideone.com/UK1RYg - and here is the solution to use today and show in minute and second hour: http://answall.com/questions/156717/70

  • Thank you Bacco! I will see everything you sent me.

Show 3 more comments

2

Take the amount getTimestamp() of the two dates and subtracts one from the other, finally divided by 60 who are the second.

$dt1 = DateTime::createFromFormat('d/m/Y H:i', '04/10/2016 14:00');
$dt2 = DateTime::createFromFormat('d/m/Y H:i', '04/10/2016 14:31');


function diff_real_minutes(DateTime $dt1, DateTime $dt2)
{
    return abs($dt1->getTimestamp() - $dt2->getTimestamp()) / 60;
}


echo diff_real_minutes($dt2, $dt1);

Functional example

Have examples here with the package Nesbot/Carbon, which is a package for dates widely used in the world , but, can be installed outside the framework which also has this logic of calculation shown above.

<?php

use Carbon\Carbon;

require_once "vendor/autoload.php";

$data_old = Carbon::createFromFormat('d/m/Y H:i', '04/10/2016 15:00');
$data_now = Carbon::createFromFormat('d/m/Y H:i', '04/10/2016 15:31');

$diff = $data_now->diffInMinutes($data_old);

var_dump($diff);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.