简体   繁体   中英

Converting integer to time format

I am looking for a nice way to convert an int into a time format. For example, I take in the integer 460 and it returns 5:00, or the integer 1432 and it returns 14:32. The only way I could think of would be tediously turning it into a string, breaking it into two strings, and checking both strings for correctness.

Thank you.

Since your examples aren't quite precise, it's hard to give a straight answer. You haven't said how would you want to store the time after conversion. Do you have some kind of class, or just wanna store it in a string ? If the latter, you'll probably use a stringstream :

unsigned int number = 460;

std::stringstream parser;
if((number/100)+(number%100)/60<10) parser << "0";  // trailing 0 if minutes < 10
parser << (number/100)+(number%100)/60              // minutes
       << ':';                                      // separator
if((number%100)%60<10) parser << "0";               // trailing 0 if seconds < 10
parser << (number%100)%60;                          // seconds

std::string time = parser.str();

Note hovewer that that's not the best way to do it. C++ provides a <ctime> header which includes the tm struct, and it would be better if you used that instead.

For easy compatibility and portability, you might want to look at the standard C runtime library functions for managing a time_t . It represents time in seconds since 1970-01-01T00:00:00 +0000 UTC.


Now that you have posted your intent (4 minutes 32 seconds stored as 432), be aware that simple calculations using this format are not straightforward. For example, what is 30 seconds later from 4:32? It would appear to be 462.

As I pointed out in my comment, I think your representation is highly problematic. I propose that you represent everything as seconds, and use some simple calculations for parsing the minutes/hours.

class PlayTime {
    size_t sec;

  public:
    PlayTime(size_t hours = 0, size_t minutes = 0, size_t seconds = 0)
      : sec(hours*60*60 + minutes*60 + seconds) {}

    size_t hours() const { return sec/(60*60); }
    size_t minutes() const { return (sec/60)%60; }
    size_t seconds() const { return sec%60; }

    PlayTime & operator +=(const PlayTime &that) {
        this-> sec += that.sec;
        return *this;
    }
};

PlayTime operator+(PlayTime a, Playtime b) { return a+=b; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM