Google Sheets – Formatting Duration Values

formattinggoogle sheets

I have a Google Spreadsheets in which I have:

 Date         | Start       | End         | Duration
 -------------+-------------+-------------+-------------------------
 11/24/2014   | 8:36 AM     | 10:12 AM    | ?
 ------------+--------------+-------------+-------------------------
 11/24/2014   | 8:06 AM     | 5:12 PM     | ?
 -------------+-------------+-------------+-------------------------     
              |             |             | 

I want to calculate the duration and format it as [hr].[fraction of hour]. So, for the first row, the duration field would show 1.6. For the second row, the value would show 9.1.

Currently, I have the start and end columns formatted as times using h":"mm" "am/pm. I do not know how to do the conversion to [hr].[fraction of hour].

How do I do this in my Google spreadsheet?

Best Answer

I had a similar problem. I needed to create a timesheet. You need to use the Script Editor. You can open that using Tools -> Script editor... in your Google Sheet. Once there, add the following code to format a duration value in a Google sheet.

function FormatDuration(duration) {
  // Retrieve the hours and minutes
  var hrs = duration.getHours();
  var mins = duration.getMinutes();

  // Rounding the minutes to tenths of an hour
  var tenths = ((mins / 60).toFixed(1) * 10);
  if (tenths === 10) {
    tenths = 0;
    hrs = hrs + 1;
  }

  // Convert the result to a number to use in calculations
  var result = hrs + '.' + tenths;
  return Number(result);
}

I hope it helps.