Public Group

My mind is blanking out, Help with subtracting time

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

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 on other sites
Just do it with borrowing, like you'd do this by hand.

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

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 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 on other sites
Is TimeStamp your own class? If not, where does it come from? If so, could we see it please?

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 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.

1. 1
2. 2
3. 3
Rutin
18
4. 4
5. 5
JoeJ
12

• 14
• 22
• 9
• 31
• 18
• Forum Statistics

• Total Topics
632617
• Total Posts
3007475
• Who's Online (See full list)

There are no registered users currently online

×