...

View Full Version : comparing am and pm of time



sradha
03-10-2010, 04:54 PM
Hello....I want to compare whether the current time is between 2 time and the code goes like
$curtime=date("h:i:s a");
if(($t1<=$curtime)&&($curtime<=$t2))
{//some code}
else{//code}
here values of $t1 and $t2 are obtained from database.t1 and t2 are obtained in the format like "08:15:00 pm".Using this code and format comparison is ok but problem is in the case with 'am' and 'pm'.It's not possible to compare time based on am and pm.For example if the current time is 10:15:10 pm and $t1=10:09:10 am and $t2=10:25:00 am then 'else loop' should get executed...right??but with this code 'if loop' gets executed...so someone plzzz help me.

mlseim
03-10-2010, 08:20 PM
Here's my shot at it ....



<?PHP

// Set the timezone to your city .. based on a valid city identifier.
// See: http://www.php.net/manual/en/timezones.php
date_default_timezone_set('America/Chicago');

// Get current time and convert to integer ...
// Example: 13:34:50 would become 133450
$curtime=date("His");

// Test variables - for this example
$t1="11:58:00 am";
$t2="05:00:05 pm";

// Compare stuff
if((conv($t1)<=$curtime)&&($curtime<=conv($t2))){
echo "Current time is between T1 and T2.<br />";
}

// Testing variables - for this example.
echo "Current Time: $curtime <br>";
echo "T1: ".conv($t1)." <br>";
echo "T2: ".conv($t2)." <br>";

// Function to convert time 24 hour mode and convert it to integer.
function conv($time){
// get am pm
$ampm=explode(" ",$time);
// get H:M:S
$hms=explode(":",$ampm[0]);

// figure out noon vs midnight, convert to 24 hour time.
if($hms[0]==12 && $ampm[1]=="am"){
$hms[0]="00";
}
else{
if($ampm[1]=="pm"){
if($hms[0]<12){
$hms[0]=$hms[0]+12;
}
}
}

// build the integer
$build=$hms[0].$hms[1].$hms[2];
return $build;
}

?>



Here's what my output looks like when I run the script above:

Current time is between T1 and T2.
Current Time: 143035
T1: 115800
T2: 170005


.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum