How to calculate the time between two DateTimes?

I know that you can use daysBetween() for two Date objects, but what would I use to calculate the elapse time in seconds between two DateTime objects?

Answer

You can use the getTime method to get the milliseconds between them and then convert to whatever unit you need:

Long dt1Long = DateTime.now().addDays(-1).getTime();
Long dt2Long = DateTime.now().getTime();
Long milliseconds = dt2Long - dt1Long;
Long seconds = milliseconds / 1000;
Long minutes = seconds / 60;
Long hours = minutes / 60;
Long days = hours / 24;

Attribution
Source : Link , Question Author : Robert Sösemann , Answer Author : BarCotter

Leave a Comment