2

Is there any method for getting duration between two time instances in hours and minutes ?

0

1 Answer 1

1

Same method as here but with just the time components.

You could get a little more fancy and just use remainders depending on your needs...You could do this without the wrapper class, but it may be more confusing to return a Time instance than to add an Interval wrapper.

public class Interval
{
    // allow for read only access through VF
    public Long milliseconds { get; private set; }
    public Long seconds { get; private set; }
    public Long hours { get; private set; }
    public Long minutes { get; private set; }

    public Interval(Time startTime, Time endTime)
    {
        Datetime todayStart = Datetime.newInstance(Date.today(), startTime);
        Datetime todayEnd = Datetime.newInstance(Date.today(), endTime);

        milliseconds = todayEnd.getTime() - todayStart.getTime();
        seconds = milliseconds / 1000;
        minutes = seconds / 60;
        hours = minutes / 60;
        //if you really want the duration you have to take the remainder
        minutes = Math.mod(minutes, 60);
        seconds = Math.mod(seconds, 60);
        milliseconds = Math.mod(milliseconds, 1000);
    }
}

And a simple test...

class IntervalTests
{
    static testMethod void testInterval()
    {
        Time startTime = Time.newInstance(0, 0, 0, 0);
        Time endTime = Time.newInstance(16, 32, 4, 8);

        Test.startTest();
            Interval between = new Interval(startTime, endTime());
        Test.stopTest();

        system.assertEquals(16, between.hours, 'Implement a message here');
        system.assertEquals(32, between.minutes, 'Implement a message here');
        system.assertEquals(4, between.seconds, 'Implement a message here');
        system.assertEquals(8, between.milliseconds, 'Implement a message here');
    }
}

Not the answer you're looking for? Browse other questions tagged .