Jump to content
  • Advertisement
Sign in to follow this  
Concentrate

My mind is blanking out, Help with subtracting time

This topic is 2783 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

Ex) I have two time

//fomat : day/month/year/hour/minutes/sec
31 dec 2008 23 59 56
1 jan 2009 0 0 17


and I want to find the difference in seconds;

My first though was to convert it into seconds like so :

//NOTE : month are only Dec or Jan

double toSeconds(const TimeStamp& t){
int month = t.month == "Jan" ? 1 : 12;
return (t.year*31556926 + month*2629743.83 + t.day * 86400 + t.min*60 + t.sec);
}


But the problem is overflow. I need another way. Any advice?

Share this post


Link to post
Share on other sites
Advertisement
Just do it with borrowing, like you'd do this by hand.



dSeconds = aSeconds - bSeconds;
if (dSeconds<0)
{
dSeconds += 60;
aMinutes -= 1;
}

etc.

Share this post


Link to post
Share on other sites
When you hit 60 seconds just subtract one from the minute variable likewise when you hit 60 minutes subtract one from the hour variable and set the minutes to 0.


if (minutes == 60)
{
hours -= 1;
}

if (seconds == 60)
{
minutes -= 1;
}

Share this post


Link to post
Share on other sites
Just make sure you use doubles everywhere, by putting a dot (".") at the end of each numeric constant. You shouldn't have any problems with overflow then.

Share this post


Link to post
Share on other sites
Is TimeStamp your own class? If not, where does it come from? If so, could we see it please?

Share this post


Link to post
Share on other sites
Oh, wait. Overflow is not your only problem. You can't just convert from years and months to seconds by multiplying by a couple of constants.

You should just use mktime, which does precisely what you want.

Share this post


Link to post
Share on other sites
Yep, what Alvaro said. Calculating the time manually is complicated, you will need to consider leap years and other quirks in the calendar system, which is pain in the arse. Use standard functions and libraries to do this.

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!