Calculate difference between two epoch times

I’m having trouble trying to figure out the difference, in minutes, between two epoch times.

Here’s a snippet of my code:

long curTime = now.unixtime();
long startTime = thisOne.unixtime();
Serial.println(abs(curTime - startTime));

The value for curTime (when I wrote this) was: 1431420380
The value for startTime (when I wrote this) was: 1431465120

The Serial.println produced: 20796, which makes no sense, since when I do that calculation on my fancy calculator, it comes back with 44,740.

What am I doing wrong here? Why is Arduino messing up the math (or just printing it incorrectly)?

Is there an easier/better way to calculate the difference (in minutes or seconds) between two epoch timestamps?

Thanks!
-Danny

Hmm...I took out the abs() and now it's giving me the correct value. Is there an abs() equivalent for long values?

Hmmm… 20796+44740 = 65536, or 216.

You need to do unsigned arithmetic. Signed arithmetic with long is also called Two’s Complement. Which means you should do this instead:

unsigned long curTime = now.unixtime();
unsigned long startTime = thisOne.unixtime();
Serial.println( curTime - startTime );

Cheers,
/dev

abs() is for ints
(and you are not using ints)
labs() is for longs
llabs() is for long longs

Look at the man page for abs() it will show all the various forms of the functions.

Not sure which library you are using but most use a time_t type to represent the time so you should use the type that the library uses rather than use a native type.
The reason being is that there is no guarantee what a time_t is or how many bits it is. Many now use 64 bits and while some still use 32 bits, in 32 bit environments many use an unsigned long to try to avoid the upcoming 2038 issue that happens when 32 bit time rolls over since bit 31 gets set in January 2038.

But you should not need to deal with this as long as you use the proper type and create a delta.

delta = time2 - time1;

The issue you may run into is if for some reason you don't know which is time1 vs time2 and always want a positive delta.
In that case, you will have to do some compile time conditional checks to make sure you are using the proper "abs" function for the width of your data if your library doesn't provide such a function. Not hard but a bit messy.

However, once you have a delta in time_t you will still need to convert that to whatever you want to see:
seconds, minutes, hours... etc...

This is because a time_t is not guaranteed to be seconds, you must then use functions, or macros provided by the library to do the conversion to what you want.

--- bill

osmosis311:
Is there an abs() equivalent for long values?

If you might not guess it correctly: Yes!

The name for the function abs() to work with long variables is labs():
labs() function in AVR LIBC