danjbh
danjbh

Reputation: 615

Comparing datetimes in php

I am comparing a date with a datetime and I get the result I expect however I also am wondering if there is a better way to display my output and I have a query on my current output also.

Here is a snippet of my current code:

<?php

$todayDate = date('Y-m-d');

$seconds = strtotime($todayDate) - strtotime($dueDate);
$hours = $seconds / 60 / 60;
echo number_format($hours, 2);
?>

in my case $dueDate in my database here is 2017-06-26 09:11:28 so the output is displaying as -57.19. My question, is there is a clean way to strip the - and also add h after the hours and m after the minutes so the output looks like this?

57h 19m

UPDATE

So After tinkering around I have managed to do this:

substr($dateFormat,0,3).'h '.substr($dateFormat,4).'m';

The output now is -57h 19m

I still have this negative character, im not sure if that is actually correct I cannot seem to work it out because the date in my database is a day ahead but it shows a negative value...

Upvotes: 0

Views: 76

Answers (3)

RiggsFolly
RiggsFolly

Reputation: 94642

Using the DateTime class makes it very simple

$dueDate = '2017-06-26 09:11:28';

$due = DateTime::createFromFormat('Y-m-d H:i:s', $dueDate);
$today = new DateTime();

$diff = $today->diff($due);

echo $diff->format('%hh %im');

Result:

11h 37m

But as you asked about timezones, here is how to add those in as well. And also as you orignial date was in fact some days distant I added a more accurate difference output

$dueDate = '2017-06-25 00:00:00';

$due = DateTime::createFromFormat('Y-m-d H:i:s', $dueDate, new DateTimeZone('Europe/London'));
$today = new DateTime('now', new DateTimeZone('Europe/London'));

$diff = $today->diff($due);

echo $diff->format('%R %hh %im').PHP_EOL;

if ( $diff->invert ) {
    echo $diff->format('Overdue by %dd %hh %im');
} else {
    echo $diff->format('You have %dd %hh %im till overdue');
}

Results

+ 1h 6m
You have 0d 1h 6m till overdue

Upvotes: 4

Osama
Osama

Reputation: 3040

use floor and round functions to get the minutes and hours after convert the date to positive sign using abs function

<?php
    $todayDate = date('Y-m-d');
    $dueDate = "2017-06-26 09:11:28";
    $seconds =abs(strtotime($todayDate) - strtotime($dueDate));
    $hours =floor($seconds / 60 / 60);
    $minutes= round($seconds / 60 / 60 - $hours,2)*100;
    echo "<br>";
    echo $hours. " H :";
    echo $minutes. " M ";
    ?> 

Upvotes: 0

You need to keep date integer

$time = time();

after

you can use this every where and evert way

For example

$date1 = time();
$date2 = time();

$comparingdate = $date2 - $date1;

$myFormat = date("T-m-d h:i:s",$comparingdate); // Show how you want

Upvotes: 0

Related Questions