Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Converting 24 hour time back into 12 hour

by theorbtwo (Prior)
on Nov 07, 2004 at 09:40 UTC ( [id://405871]=note: print w/replies, xml ) Need Help??


in reply to Converting 24 hour time back into 12 hour

I looked through this thread, and was amazed that nobody implemented a correct, lossless implementation. Generally, when you write a 12-hour time, you should include "AM" or "PM", because otherwise you loose information. Thus, I'm adding my solution:

sub to12h { local $_=shift; return (12, "PM") if $_==0; return ($_, "AM") if $_<=12; return ($_-12, "PM") } for (0..23) { print join " ", to12h($_), "\n"; }

Of course, if you /want/ to loose information, just use the first element of the return value.


Warning: Unless otherwise stated, code is untested. Do not use without understanding. Code is posted in the hopes it is useful, but without warranty. All copyrights are relinquished into the public domain unless otherwise stated. I am not an angel. I am capable of error, and err on a fairly regular basis. If I made a mistake, please let me know (such as by replying to this node).

Replies are listed 'Best First'.
Re^2: Converting 24 hour time back into 12 hour
by jfroebe (Parson) on Nov 07, 2004 at 16:57 UTC

    hi,

    slight correction:

    sub to12h { local $_=shift; if (($_ < 0) || ($_ > 23)) { return ("$_ is not a valid hour"); } return ($_, "AM") if $_ < 12; return ($_, "PM") if $_ == 12; return ($_ -12, "PM") } for (0..23) { print join " ", to12h($_), "\n"; }

    Jason L. Froebe

    Team Sybase member

    No one has seen what you have seen, and until that happens, we're all going to think that you're nuts. - Jack O'Neil, Stargate SG-1

      Thanks.
      one more correction - you have forgot to convert 24hr's 00 hours to 12AM
      sub to12h { local $_=shift; if (($_ < 0) || ($_ > 23)) { return ("$_ is not a valid hour"); } return (12, "AM") if $_ == 0; return ($_, "AM") if $_ < 12; return ($_, "PM") if $_ == 12; return ($_ -12, "PM"); } for (0..23) { print join " ", to12h($_), "\n"; }
        there is no such thing as 24:00hrs...

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://405871]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (5)
As of 2024-04-23 15:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found