Question

How can i find the difference of 2 datetime fields in days ?

I couldnt find anything on the documentation for this. i can see that there are methods to add hours, days but cant find anything on getting the datedifference.

The one way i can think of is to convert both fields into datetime using valueof and use the date function daysbetween.

    integer Days__c = Date.today().daysBetween(date.valueof(datetimefield__c));

Any are there any other better options?

Was it helpful?

Solution

You could do this:

integer Days = Integer.valueOf((Date2.getTime() - Date1.getTime())/(1000*60*60*24));

This would convert each date into milliseconds, subtract one from the other, then convert it into integer of days. or could convert into decimal days.

OTHER TIPS

Datetime startDate = system.now();// Start date
Datetime endDate = system.now().addHours(60);//End Date

Integer noOfDays = startDate.Date().daysBetween(endDate.Date());
System.debug('No Of Days : '+noOfDays);

Datetime sameDayEndDate = startDate.addDays(noOfDays);
System.debug('Same Day : '+sameDayEndDate);

Decimal decHours = ((endDate.getTime())/1000/60/60) - ((sameDayEndDate.getTime())/1000/60/60);
System.debug('Dec Hours : '+decHours); 

decimal decMinutes = ((endDate.getTime())/1000/60) - ((sameDayEndDate.getTime())/1000/60);
System.debug('Minutes : '+decMinutes);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top