• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 406
  • Last Modified:

Php - Compare data and time and output the difference

Hi E's, I need to know how I compare two times and output th difference between them.
In practice I have two time, compose by the day and the hours:
$old_time = "2012-09-20";
$old_hour = "23:10:57"; //(hour:minutes:seconds)
$actual_time = "2012-09-21";
$actual_hour = "13:17:44"; //(hour:minutes:seconds)
$difference = "days:hours:minutes:seconds"; //difference between old time and actual time

How I get the result of $difference variable?

The best regards, JC
0
Pedro Chagas
Asked:
Pedro Chagas
  • 2
1 Solution
 
Julian HansenCommented:
$t1 = strtotime($old_time . ' ' . $old_hour);
$t2 = strtotime($actual_time . ' ' . $actual_hour);
$difference = $t2 - $t1;

Open in new window

0
 
Julian HansenCommented:
Full code to get time string
$old_time = "2012-09-20";
$old_hour = "23:10:57"; //(hour:minutes:seconds)
$actual_time = "2012-09-21";
$actual_hour = "13:17:44"; //(hour:minutes:seconds)

$t1 = strtotime($old_time . ' ' . $old_hour);
$t2 = strtotime($actual_time . ' ' . $actual_hour);
$difference = $t2 - $t1;

$days = intval($difference / 86400);
$hours = intval(($difference % 86400) / 3600);
$min = intval(($difference % 3600) / 60);
$sec = $difference % 60;
$diffstr = sprintf("%02d:%02d:%02d:%02d", $days, $hours, $min, $sec);
echo $diffstr;

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now