How to calculate the time between two DateTimes?
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;
I know this is kind of late, but I had a similar need for elapsed time which may help in your case.
So I created the following utility:
public static Time GetElapsedTime(Time startTime, Time endTime)
{
if(startTime == null || endTime == null)
return Time.newInstance(0, 0, 0, 0);
Integer elapsedHours = endTime.hour() - startTime.hour();
Integer elapsedMinutes = endTime.minute() - startTime.minute();
Integer elapsedSeconds = endTime.second() - startTime.second();
Integer elapsedMiliseconds = endTime.millisecond() - startTime.millisecond();
return Time.newInstance(elapsedHours, elapsedMinutes, elapsedSeconds, elapsedMiliseconds);
}
Now that I have an elapsed time method, I could get my elapsed time as a Time object and do whatever I see fit. So for example, if you needed seconds elapsed for two DateTimes, you could use another method on-top of the one I put above.
So you can create another method like so:
public static Integer GetSecondsElapsed(Time startTime, Time endTime)
{
return GetElapsedTime(startTime, endTime).second();
}
You can then call the method with your DateTimes like:
Integer secondsElapsed = YourUtilityClass.GetSecondsElapsed(YourDateTimeOne.time(), YourDateTimeTwo.time());
You could go a step further and do the following as well:
public static Time GetElapsedTime(DateTime startDate, DateTime endDate)
{
if(startDate == null || endDate == null)
return Time.newInstance(0, 0, 0, 0);
return GetElapsedTime(startDate.time(), endDate.time());
}
Then have the following method:
public static Integer GetSecondsElapsed(DateTime startDate, DateTime endDate)
{
return GetElapsedTime(startDate, endDate).seconds();
}
Now your utility will look something like this:
Integer secondsElapsed = YourUtilityClass.GetSecondsElapsed(YourDateTimeOne, YourDateTimeTwo));
This will now give you the flexibility you need. I needed the elapsed time in a readable format, so simply getting the string value of the time elapsed was suitable for me.