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?

  • BarCotter

    BarCotter Correct answer

    7 years ago

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

    Long dt1Long =;
    Long dt2Long =;
    Long milliseconds = dt2Long - dt1Long;
    Long seconds = milliseconds / 1000;
    Long minutes = seconds / 60;
    Long hours = minutes / 60;
    Long days = hours / 24;

    No reason to create manual functions for this, getTime() is exactly what you want; from the docs: > Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this DateTime object.

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM

Tags used