karthik
karthik

Reputation: 36

time difference calculating using php?

I find it difficult to calculate time difference using PHP. How to calculate time difference in HH:MM:SS format (hours:minutes:seconds) between two different dates?

For example, the input is:

$start_time : 19:30  
$end_time : 7:30,  
$currenttime = 21:30  

I have to find out current time has match with given start time and end time.

Upvotes: 0

Views: 257

Answers (2)

Niclas Larsson
Niclas Larsson

Reputation: 1317

$iStart = strtotime( '00:00:00' );
$iEnd = strtotime( '12:00:00' );

$iCurrent = strtotime( date('H:i:s') );

if( $iCurrent > $iStart && $iCurrent < $iEnd ) {
  echo "active!";
} else {
 echo "not active";
}

This will only respect the time (it will be active once a day). If you need specific dates you can use:

$iStart = strtotime( '2012-12-01 00:00:00' );
$iEnd = strtotime( '2012-12-31 12:00:00' );

$iCurrent = time();

if( $iCurrent > $iStart && $iCurrent < $iEnd ) {
  echo "active!";
} else {
 echo "not active";
}

Upvotes: 1

GolezTrol
GolezTrol

Reputation: 116190

Convert the times to a timestamp value, which is an integer value in seconds. Then, you can subtract them easily to get the difference in seconds. After that, it's pretty straightforward to convert that back to hours and minutes.

Upvotes: 1

Related Questions