# Get the days and hours between two datetimes in decimal format

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 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;
}
}
``````

You can utilize Datetime's getTime() method and compare the two values.

``````Datetime firstTime = Datetime.newInstance(2016, 9, 22, 12, 30, 0);
Datetime secondTime = Datetime.newInstance(2016, 9, 23, 14, 00, 0);

Decimal millisecondsBetween = secondTime.getTime() - firstTime.getTime(); //NB: ths is important as to convert type
Decimal timeBetween = millisecondsBetween / 86400000;  //1000 * 60 * 60 * 24
System.debug(timeBetween);
``````

Above is the sample code. I got the value 1.0625 which I think is correct. Please Note you need to convert the type into Decimal before divided by 86400000. Otherwise, the result would be 1.

• I tried it. now.getTime() - lastDate.getTime() but the numbers didnt make calculate correctly. – user8310 Sep 28 '16 at 22:51
• @user8310 I edited and added the code. It works for me. – Lance Shi Sep 28 '16 at 22:57
• I made the following changes but still seems like the timing is a bit off. public static Decimal getTimeDifference(Datetime now, Datetime endTime){ if(now != null && endTime != null){ Decimal millisecondsBetween = now.getTime() - endTime.getTime(); //NB: ths is important as to convert type Decimal timeBetween = millisecondsBetween / 86400000; //1000 * 60 * 60 * 24 System.debug(timeBetween); return timeBetween.setScale(2); } else { return null; } } – user8310 Sep 28 '16 at 23:20
• @user8310 what do you mean by timing is a bit off? I am getting 1.06 using your code, which seems correct to me – Lance Shi Sep 28 '16 at 23:25
• that's absolutely correct. There is 1 day and 1.5 hours difference, which results in 1 + (1.5/24) = 1.0625. Not sure what does OP mean by timing is a bit off – Novarg Sep 29 '16 at 7:34