CG_man has asked for the wisdom of the Perl Monks concerning the following question:

Trying to get 12 hr time to display rather than 24 hr time. Right now my time stamp is 18:45:13 11/13/2008. I need it to be 6:45pm 11/13/2008. Here is what I have now
sub GETTIME { if ($_[0] eq "999999999") { $time = ("******** **********"); } elsif ($_[0] eq "0") { $time = ("******** **********"); } else { ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime( +$_[0]); $mon++; $time = sprintf ("%.2d:%.2d:%.2d %.2d/%.2d/%.2d", $hour, $min, $se +c, $mon, $mday, $year + 1900);
I appreciate any help on this. Not sure if I can do what I want using localtime.
  • Comment on How do I convert localtime to display 12 hr time instead of 24 hr time
  • Download Code

Replies are listed 'Best First'.
Re: How do I convert localtime to display 12 hr time instead of 24 hr time
by ikegami (Patriarch) on Nov 14, 2008 at 04:03 UTC
    my ($sec, $min, $hour, $mday, $mon, $year) = localtime($_[0]); $mon += 1; $year += 1900; $ampm = ( $hour < 12 ? 'am' : 'pm' ); $hour %= 12; $hour += 12 if !$hour; $time = sprintf("%d:%02d%s %d/%02d/%02d", $hour, $min, $ampm, $mon, $mday, $year );
    or
    use POSIX qw( strftime ); # Formats as "6:45pm 10/31/2008" $time = strftime('%I:%M%p %m/%d/%Y', localtime($_[0]));

    Update: Added surrounding code to show other improvements and to contrast complexity with strftime version.

      Nice !! Ikegami, worked perfect, I searched every where for a converter code, thanks for the help, have a great holiday season
Re: How do I convert localtime to display 12 hr time instead of 24 hr time
by eighty-one (Curate) on Nov 14, 2008 at 04:09 UTC
    Or
    $ampm = ( $hour < 12 ? 'am' : 'pm' ); if($hour > 12){ $hour -=12; }

    (I would have overlooked the am/pm requirement if someone hadn't gotten here first . . . Thanks ikegami ;)

    Whenever I have a time question I usually go to The many dates and times of Perl but I didn't see anything applicable there. Of course, I'm sleepy and very well may have overlooked something.

Re: How do I convert localtime to display 12 hr time instead of 24 hr time
by ysth (Canon) on Nov 14, 2008 at 08:24 UTC