1

I am getting the difference in time between two date/time fields. I need to show the time in hours:minutes in another field.

Long timeOpen = BusinessHours.diff(bh.Id, ar.Date_Time_Assigned__c, ar.Completed_Canceled_Date_Time__c);
Long seconds = timeOpen / 1000;
Long minutes = seconds / 60;
Long hours = minutes / 60;
ar.Time_Open__c = hours;

Right now, I'm only getting the hours, but I need to include the minutes too.

4
  • 1
    What is the field type of "Time_Open__c"? Nov 14, 2014 at 4:59
  • Last time I checked, minutes = seconds * 60 and hours = minutes * 60. Did you perhaps mean to put minutes = timeOpen / 60 or were you looking to get the integerValue of timeOpen / 60 and then use the remainder to do your calculations with for minutes, and similarly for seconds, etc?
    – crmprogdev
    Nov 14, 2014 at 5:51
  • Meant to add that the remainder would be the mod. See Math Methods in the Apex Code Developer's Guide for more.
    – crmprogdev
    Nov 14, 2014 at 5:59
  • If you dont need to do it via apex, I recommend looking at this which was accomplished via formula. salesforce.stackexchange.com/questions/50130/…
    – Double A
    Dec 30, 2014 at 21:50

2 Answers 2

1

If you look at my answer to the following question here, I created a very simple time difference utility to return the time difference between two Time instances or two DateTime instances.

From there you can extend the utility with the following to get what you want:

public static String GetHourAndMinuteDisplay(DateTime startDate, DateTime endDate)
{
    return GetElapsedTime(startDate, endDate).format('hh:mm');
}

If you need to get hours or minutes separately, it's rather straight-forward.

For hours:

public static Integer GetElapsedHours(DateTime startDate, DateTime endDate)
{
    return GetElapsedTime(startDate, endDate).hour();
}

For minutes:

public static Integer GetElapsedMinutes(DateTime startDate, DateTime endDate)
{
    return GetElapsedTime(startDate, endDate).minute();
}
0

You can use the following formula to get the correct answer of ur question: It will return hour, min, sec and AM or PM Datetime.now().format('hh:mm:ss a');

You must log in to answer this question.

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