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 = 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;
    

    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