Jump to content
  • Advertisement
Sign in to follow this  
phil05

C++: Is there a function that converts seconds into time? (12:59:59)

This topic is 5457 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Advertisement
I don't know of any, but it shouldn't be that hard.

Assuming you mean converting 900 seconds into 15 minutes sort of thing, it's fairly simple:


iTotalSeconds = Number of Total Seconds

int iHours = 0, iMinutes = 0, iSeconds = 0;

while(iTotalSeconds >= 3600) // 3600 seconds in an hour.
{
Add 1 to iHours
Subtract 3600 from iTotalSeconds
}

while(iTotalSeconds >= 60) // 60 seconds in a minute
{
Add 1 to iMinutes
Subtract 60 from iTotalSeconds
}


Add the rest to iSeconds and you've got your 3 variables, ready to output however you want.

Make sense?

Share this post


Link to post
Share on other sites
{seconds an int}
int hours = seconds / 3600;
int minutes = (seconds % 3600) / 60;
int seconds = seconds % (60);

Share this post


Link to post
Share on other sites
Okay, I tried translating that and got this so far.


long Secs_To_Time(long TS) // TS = aka Total Seconds
{
long Hours = 0, Minutes = 0, Seconds = 0;

while (TS >= 3600) // 3600 seconds is an hour
{
Hours += 1;
TS = TS - 3600;
}

while (TS >= 60) // 60 seconds in a minute
{
Minutes += 1;
TS = TS - 60;
}

while (TS != 0) // Rest in Seconds
{
Seconds += 1;
TS = TS - 1;
}

}


Share this post


Link to post
Share on other sites
Quote:
Original post by CJH
{seconds an int}
int hours = seconds / 3600;
int minutes = (seconds % 3600) / 60;
int seconds = seconds % (60);

Nice! Oddly, in all my programming years, I never thought to do it that way. Of course, that's assuming it works, which it looks like it does.

Share this post


Link to post
Share on other sites
Quote:
Original post by philvaira
Okay, I tried translating that and got this so far.

*** Source Snippet Removed ***

That looks great, except that the last while loop is unnecessary. Everything left in TS at that point will go to seconds, so you could replace the whole while loop with

Seconds = TS;

Share this post


Link to post
Share on other sites
Quote:
Original post by CJH
{seconds an int}
int hours = seconds / 3600;
int minutes = (seconds % 3600) / 60;
int seconds = seconds % (60);


This would work too, but you never actually modify the seconds variable, which means your calculation of int seconds = (seconds) will be off. No?

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!