Coverting 24 hour time to 12 hour in C++

Hi there,
I want to convert a string  time in format "HH:MM:SS" into a 12 hour time.  So, for example
13:22:22 becomes 01:22:22 PM( I want it to be double digit)

I have come up with the following code.  But, is there a simple way to do this....
Thanks,

string change2(string time24Hour)
{
    stringstream time12Hour;
    int hh, mm, ss;
    sscanf(time24Hour.c_str(), "%d:%d:%d", &hh, &mm, &ss);
    string suffix;

    if(hh >=12 )
    {
        suffix = "PM";
    }
    else
    {
        suffix = "AM";
    }

    if (hh > 12)
    {
        hh = hh - 12;
        time12Hour << std::setw(2) << std::setfill('0') << hh << ":" << mm << ":" << ss;
    }
    else
    {
        time12Hour << std::setw(2) << std::setfill('0') << hh << ":" << mm << ":" << ss;
    }
    time12Hour << " " + suffix;
    return time12Hour.str();
}

Open in new window

ambuliAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

AndyAinscowFreelance programmer / ConsultantCommented:
There is a function to format times:
http://www.cplusplus.com/reference/ctime/strftime/
arnoldCommented:
The problem one is going from string format in one way to a string format in another.

If(hh >=12 )
    {
        suffix = "PM";
     hh=   (hh>12) ? hh-12:hh;
    }
    else
    {
        suffix = "AM";
    }

Open in new window


On the output side check if hh <=9  and use the reverse sprintf(time12hour.c_str(),"%s:%s:%s %s", (hh <=9)? ..... C
phoffric\Commented:
If high performance is an issue, then you would want to improve on this, just as you would want to improve your OP.
#include <string>
#include <cstring>
#include <cstdio>
#include <iostream>
#include <cstdlib>

string change2(string time24Hour)
{
   char buf[3];
   int hh = atoi(time24Hour.c_str());
   string suffix = hh > 11 ? "PM" : "AM";
   hh = hh > 12 ? hh - 12 : hh;
   sprintf(buf, "%02d", hh);

   return string(buf) + time24Hour.substr(2, string::npos) +  " " + suffix;
}

Open in new window

Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

sarabandeCommented:
it probably is not so much better but pure c++.

std::istringstream iss(time24Hour.substring(0,2));
int hour;
if (iss >> hour)
{
      if (hour >= 12)
      {
           std::ostringstream oss;
           oss << std::setw(2) << std::right << std::setfill('0') << hour-12;
           time24Hour.replace(0,2, oss.str());
           time24Hour += " PM";
      }
      else 
          time24Hour += " AM";

Open in new window


Sara
phoffric\Commented:
As for my post, I built it with g++ (a pure C++ compiler). Furthermore, every construction in my post is in the ISO C++ specification. As such, the post represents "pure" C++.
sarabandeCommented:
sprintf is c runtime. it is neither safe and not "pure" c++.

Sara
sarabandeCommented:
printf and sprintf are unsafe cause they could be manipulated from malware to infect valid code. for example if you achieve to replace a "%d" in a format by a "%s", the stack variable passed as argument in printf or sprintf no longer was interpreted as an integer but as a pointer to char and so could cause a buffer overflow. worse, those c functions even could "read" into memory and so be used for manipulating the stack and implementing malware this way. this might rarely happen for most of applications but actually using c++ streaming instead of functions like sprintf or scanf, you simply have a safe method while otherwise you have an unsafe method.

Sara
phoffric\Commented:
Thank you for bringing up cyber security issues. I expect that the author intended this question to be about cyber security.

I do not understand your definition of pure C++ code. Please provide a link so that whether or not we agree, at least I will see your definition in web-print that may be considered correct by at least some of the professional SW community.

In my world, pure C++ code means any code that conforms to the C++ ISO standard, thereby improving the odds that the program will be portable. I don't have a link with this definition off-hand, but this is what my professional associates have professed.
ozoCommented:
Regardless of the semantics of what one calls "pure" C++ code, the proposed answer produces "00 AM" and "00 PM" instead of "12 AM" and "12 PM"
This can be corrected with
        oss << std::setw(2) << std::right << std::setfill('0') << (hour+11)%12+1;
        time24Hour.replace(0,2, oss.str());
        time24Hour += hour>=12?" PM":" AM";

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
sarabandeCommented:
ozo is right. the original post already was correct. i should have been more accurate before posting wrong code.

security issues are not relevant for the question but you will find any number of references for example  at www.owasp.org/index.php/Format_string_attack.

Sara
ozoCommented:
The original post was not correct for hh=0

phoffric's code was not vulnerable to www.owasp.org/index.php/Format_string_attack
because the "%02d" did not come from user input.
(but phoffric's code was also not correct for hh=0)
AndyAinscowFreelance programmer / ConsultantCommented:
Back to the original question.
If the string in 24 hour format comes from a datetime object then using the strftime function will provide a one line way to accomplish what is requested.  It depends on what the original data is.
sarabandeCommented:
the "%02d" did not come from user input
the main attacks occur by hijacking a program. then it is only necessary to locate the format string in memory and get access to it.

Sara
arnoldCommented:
Missed, the 00
In the else Sugfix='AM' a conditional if hh is 0 to add 12.
ambuliAuthor Commented:
Thank you all!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.