0

I have two date times of the form

Start Date: 2015-11-15 11:40:44pm 
End Date: 2015-11-22 10:50:88am

Now I need to find the difference between these two in the following form:

0 years, 0 months, 7 days, 22 hours, 44 mints, 35 sec

How can I do this in PHP?

I already try:

$strStart = date('Y-m-d h:i:s', time() - 3600);
$strEnd   = '2015-11-22 02:45:25';
$dteStart = new DateTime($strStart); 
$dteEnd   = new DateTime($strEnd);
$dteDiff  = $dteStart->diff($dteEnd);
echo $dteDiff->format("%H:%I:%S");

Output:22:53:58

Output not shown perfectly.

Imran Hossain
  • 45
  • 2
  • 2
  • 9
  • 1
    What have you tried? At least try some of the datetime functions of php, If that fails, we can help with your failing code. – Terradon Nov 22 '15 at 11:16

2 Answers2

1
$startDate = "2015-11-15 11:40:44pm";
$endDate = "2015-11-22 10:50:48am";  // You had 50:88 here? That's not an existing time

$startEpoch = strtotime($startDate);
$endEpoch = strtotime($endDate);

$difference = $endEpoch - $startEpoch;

The script above converts the start and end date to epoch time (seconds since January 1 1970 00:00:00 GMT). Then it does the maths and gets the difference between them.

Since years and months aren't a static value, I haven't added them in the script below

$minute = 60; // A minute in seconds
$hour = $minute * 60; // An hour in seconds
$day = $hour * 24; // A day in seconds

$daycount = 0; // Counts the days
$hourcount = 0; // Counts the hours
$minutecount = 0; // Counts the minutes

while ($difference > $day) { // While the difference is still bigger than a day
    $difference -= $day; // Takes 1 day from the difference
    $daycount += 1; // Add 1 to days
}

// Now it continues with what's left
while ($difference > $hour) { // While the difference is still bigger than an hour
    $difference -= $hour; // Takes 1 hour from the difference
    $hourcount += 1; // Add 1 to hours
}

// Now it continues with what's left
while ($difference > $minute) { // While the difference is still bigger than a minute
    $difference -= $minute; // Takes 1 minute from the difference
    $minutecount += 1; // Add 1 to minutes
}

// What remains are the seconds
echo $daycount . " days ";
echo $hourcount . " hours ";
echo $minutecount . " minutes ";
echo $difference . " seconds ";
1

Now I need to find the difference between these two in the following form:

0 years, 0 months, 7 days, 22 hours, 44 mints, 35 sec

So that’s your main problem here, getting this exact output structure?

Well then you simply have to format the DateInterval differently:

echo $dteDiff->format("%y years, %m months, %d days, %h hours, %i mints, %s sec");
Community
  • 1
  • 1
CBroe
  • 91,630
  • 14
  • 92
  • 150