Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Feb 2010
    Location
    God's Own Country
    Posts
    87
    Thanks
    6
    Thanked 0 Times in 0 Posts

    comparing am and pm of time

    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.

  • #2
    Master Coder
    Join Date
    Jun 2003
    Location
    Cottage Grove, Minnesota
    Posts
    9,539
    Thanks
    8
    Thanked 1,093 Times in 1,084 Posts
    Here's my shot at it ....

    PHP Code:
    <?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



    .
    Last edited by mlseim; 03-10-2010 at 09:31 PM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •