0

I have two dateTime fields, I need to get the amount of days and hours that have elapsed. This is the best i Can do but now im getting some errors.

Heres the error

System.TypeException: Invalid decimal: 0.-22

If the first date is 22/09/2016 12:30 and the second is 24/09/2016 14:00 I would want the results to be 2.1

public static Decimal getTimeDifference(Datetime now, Datetime endTime){
if(now != null && endTime != null){
    Long dt1Long = endTime.getTime();
    Long dt2Long = now.getTime();
    Long milliseconds = dt2Long - dt1Long;
    Long seconds = milliseconds / 1000;
    Long minutes = seconds / 60;
    Long hours = minutes / 60;
    Long days1 = hours / 24;

    Long dt1Long2 = endTime.addDays((Integer)days1).getTime();
    Long dt2Long2 = now.getTime();
    Long milliseconds2 = dt2Long2 - dt1Long2;
    Long seconds2 = milliseconds2 / 1000;
    Long minutes2 = seconds2 / 60;
    Long hours2 = minutes2 / 60;
    Long days2 = hours2 / 24;
    return Decimal.valueOf(days1 + '.' + hours2);
} else {
    return null;
}

}

aronowt
  • 9
  • 1
  • 6
  • This has been answered here .. http://salesforce.stackexchange.com/questions/5354/days-between-two-datetime-values-excluding-weekends – EricSSH Oct 24 '16 at 18:19

1 Answers1

0

If your first input now is the 22nd and your second endDate is the 24th. You are creating a negative millisecond value by subtracting your now by your end date

Otherwise you can refer to this Question

Community
  • 1
  • 1
Derrick Cheek
  • 147
  • 1
  • 6