Ali Rasheed
Ali Rasheed

Reputation: 2817

how to get the difference between two dates with timing

I have two dates that are in format Y-m-d

$dateOld = new DateTime("2017-01-10");
$dateNew = new DateTime("2017-01-11");

echo $diff = $dateNew->diff($dateOld)->format("%a");

this is working perfect and giving me exact days left.

But now I have added time and it is in H-M format

Like 23:38 and 17:21 and cannot understand now to get the difference between two dateTime

$dateOld = new DateTime("2017-01-10 23:38");
$dateNew = new DateTime("2017-01-11 17:21");

echo $diff = $dateNew->diff($dateOld)->format("%a");

I want to get the difference even if the value if in floating point. Now to work with date concatenated with time?

Upvotes: 0

Views: 88

Answers (2)

Kaduna
Kaduna

Reputation: 60

Use this:

<?php
$dateOld = new DateTime("2017-01-10 23:38");
$dateNew = new DateTime("2017-01-11 17:21");

$diff = $dateNew->diff($dateOld);
$days = $diff->d;
$hours = $diff->h;
$minutes = $diff->i;

$total_difference = $days + ($hours * 60 + $minutes) / 1440;

echo $total_difference;

Or, without the DateInterval:

$dateOld = new DateTime("2017-01-10 23:38");
$dateNew = new DateTime("2017-01-12 17:21");

$difference_in_seconds = $dateNew->getTimestamp() - $dateOld->getTimestamp();

$total_difference_in_days = $difference_in_seconds / 86400;

echo $total_difference_in_days;

Using ->format("%a") will give you the rounded days.

See http://php.net/manual/en/datetime.diff.php.

Upvotes: 1

zdrohn
zdrohn

Reputation: 56

$dateNew = '2017-01-11 17:21'; 
$dateOld = '2017-01-10 23:38'; 


$dateNew = new DateTime($dateNew); 
$dateOld   = new DateTime($dateOld); 

$diff  = $dateNew->diff($dateOld); 

echo $diff->format("%H:%I");

Source: http://php.net/manual/en/datetime.diff.php

Upvotes: 0

Related Questions