My mind is blanking out, Help with subtracting time

Started by
5 comments, last by Tachikoma 12 years, 12 months ago
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?
Edge cases will show your design flaws in your code!
Visit my site
Visit my FaceBook
Visit my github
Advertisement
Just do it with borrowing, like you'd do this by hand.



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

etc.
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;
}
AMD Phenom II X6 1090T 3.2GHz
XFX ATI Radeon 5770 1GB GDDR5
ASUS M4A89GTD Pro USB 3.0
CORSAIR XMS3 4GB 1600MHz
THERMALTAKE V3
SEAGATE 500GB
WINDOWS 7 ULTIMATE 64 Bit
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.
Is TimeStamp your own class? If not, where does it come from? If so, could we see it please?
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.
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.
Latest project: Sideways Racing on the iPad

This topic is closed to new replies.

Advertisement