0

I am working with PHP, I have following data (datetime) inside foreach loop, and I want to get remaining time (in minutes, how many minutes are left), but right now I am getting same response for every time. Here is my code:

$date2 = date('Y-m-d H:i'); // current date time
foreach($data as $records)
    {
       $upcoming_date=$records['start']; // dynamic date time(coming from database)
       $remainig_minutes=$date2.round(abs($date2 - $upcoming_date) / 60,2). " minute";
    }   
Don't Panic
  • 13,965
  • 5
  • 32
  • 51
coder
  • 11
  • 3
  • @MarkusZeller can i get difference without "seconds" (s) ? – coder Nov 04 '22 at 12:35
  • Do you mean to subtract `$upcoming_date` instead of `$start`? – aynber Nov 04 '22 at 12:36
  • 1
    To get in minutes use `SELECT TIMESTAMPDIFF(MINUTE, NOW(), start) AS diff` – Markus Zeller Nov 04 '22 at 12:39
  • Please form a [mcve] by providing sample data for the used variables and show us your exact desired result. – mickmackusa Nov 05 '22 at 00:28
  • What is `$date2.round()` supposed to do? Is `$records['start']` a date string, and if so, what format is it? You mention `datetime` in your text, do you mean a [PHP DateTime](https://www.php.net/manual/en/class.datetimeinterface.php), or are you talking about a [MySQL datetime string](https://dev.mysql.com/doc/refman/8.0/en/datetime.html)? – Don't Panic Nov 05 '22 at 04:07
  • @Don'tPanic format is "Y-m-d" – coder Nov 05 '22 at 04:09

1 Answers1

0

Here's a working example of the following code:

// Set up some fake data so we can run this code.  According to OP's comments,
// format is "Y-m-d".  Note that since this does not include minutes, you are 
// assuming "00:00" (midnight) on the specified day in your minute calculations.
$data = [
    ['start' => '2022-11-03'],
    ['start' => '2022-11-04'],
    ['start' => date('Y-m-d')],
];

$now = new DateTime();
echo "Now is " . $now->format('Y-m-d H:i') . "\n";

foreach ($data as $records) {
    $start = new DateTime($records['start']);
    $diff = $start->diff($now);

    // Convert days and hours to minutes, and sum them all up to get total
    // diff in minutes
    $minutes = ($diff->days * 24 * 60) + ($diff->h * 60) + ($diff->i);
    echo $start->format('Y-m-d H:i') . " was " . $minutes . " minutes ago\n";
}

I really just copied and updated this code from How to get time difference in minutes in PHP, and I vote we close this question as a duplicate of that one.

Don't Panic
  • 13,965
  • 5
  • 32
  • 51