# 12 hour clock and offset problem

I'm trying to convert an input time to the offset time in a 12 hour
clock system. It's giving me a headache. The am and pm must be the
right ones when the offset is added to the input time (\$temptime). I
understand it's better to use a 24 hour clock, but unfortunately I
can't in this situation. Everything needs to be done in 12-hour
format.

In short, 10:00 am with an offset of -3 should result in 1:00 pm;
10:00 pm with an offset of -3 should result in 1:00 am.
I've been at this for awhile, sadly, and cannot wrap my head around
it. Any help to point me in the right direction would be fantastic.

difficulty is the AM/PM to switch.

my \$offset = -3;
my \$tempTime = "10:00 pm";
sub myMod {
my ( \$a, \$b ) = @_;
my \$div = \$a / \$b;
return \$a - int( \$div ) * \$b;
}
sub getutc {
my \$time = shift;
my \$GMTOffset = shift;
\$time =~ /(\d{1,2}):(\d\d)\s(.+)*/;
# Is UTC a .5 remainder? if so, chop it off--we use
# it later regardless
my \$hours = \$1;
if (myMod(\$hours,int(\$hours)) == -0.5) {
\$hours - 0.5;
}
my \$minutes = \$2;
my \$ampm = \$3;
#Take hours and subtract whole number in Offset Time
\$hours = \$hours - int(\$GMTOffset);
if (\$hours >= 12) {
\$ampm = "pm";
\$hours = \$hours - 12
}
# If 0.5 on the Offset, then add 30 minutes and wrap
if (myMod(\$GMTOffset, int(\$GMTOffset)) == -0.5) {
\$minutes = \$minutes + 30;
if (\$minutes >= 60) {
\$minutes = \$minutes % 60;
\$hours = \$hours + 1;
}
}
\$minutes = sprintf("%02d", \$minutes);
\$hours = sprintf("%2d", \$hours);
if (\$hours == 0) { \$hours = "12";}
return \$hours.":".\$minutes." ".\$ampm;
}

my \$theTime = getutc(\$tempTime, \$offset);
print "\nCurrent time: \$tempTime\n";