Link to home
Start Free TrialLog in
Avatar of idadan
idadan

asked on

problem with date sub

I use this subroutine (orig from someone elses program) to get the time and date nicely formatted.  However instead of 1:15 it writes 13:15.  Anyone see whats wrong?  Thanks.
sub date {
      ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime (time);

      $mon++;

      if ($hour < 12) {
            $AMPM = "AM";
      }

      if ($hour > 12) {
            $hour = $hour - 12;
            $AMPM = "PM";
      }        
      if ($hour == 12) {
            $AMPM = "PM";
      }        
            
      if ($hour == 0) {
            $hour = "12";
      }
      $hour++;
      $min = sprintf ("%2d", $min);
      $min =~tr/ /0/;
      $mon = sprintf ("%2d", $mon);
      $mon =~tr/ /0/;
      $mday = sprintf ("%2d", $mday);
      $mday =~tr/ /0/;
      $HyphenDate = ("$mon" . "-" . "$mday" . "-" . "$year");
      $RunonDate = ("$mon$mday$year");
      $Time = ("$hour" . ":" . "$min" . " " . "$AMPM");
      
}
Avatar of b2pi
b2pi
Flag of United States of America image

Yup.  This thing will always give the wrong time.  The culprit is that

$hour++ ;

By the way, I'm pretty sure that you could combine the if statements as:

if ($hour < 12) {
   $AMPM = 'AM'
elsif ($hour >= 12) {
    $hour -= 12;
    $AMPM = "PM";
}
if ($hour == 0) {
    $hour += 12;
}

Avatar of idadan
idadan

ASKER

I didn't try replacing the if statements but when i took out that hour++ it gave the time as an hour off, 4:27 read as 3:27.
Avatar of idadan

ASKER

The only time it gets the time wrong is for 1:00 to 1:59 no others are wrong.
ASKER CERTIFIED SOLUTION
Avatar of b2pi
b2pi
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of idadan

ASKER

Its a unix machine running apache, I'll look into another sub, thanks for the help.
Avatar of ozo

($min, $hour) = (localtime)[1,2];
$Time = sprintf("%d:%02d %s",($hour-1)%12+1,$min,$hour<12?"AM":"PM");

use POSIX;
$Time=strftime "%I:%S %p",localtime;