0
votes

I created a simple custom function to test in google sheets script functions. The function definition is :

/**
* convert duration such as 1:30 to 1.5
 *
 * @customfunction
 */
function SIMPLETEST(input) {
  // simply return the input for now to test.
  return input;

}

and in my spread sheet I have a cell A2 that have value 3:30:00. when I apply this function on B2 for example set b2 to: =DURATION_DECIMAL(A2) it returns 12/30/1899 which I believe is base date.

Why is this happening?

2

2 Answers

1
votes

It's because you must have the data type for that cell set to "automatic" or "duration", and Google Sheets will guess that "3:30:00" is a type of date/time for automatic, and for duration it converts it to date/time for passing to your function. It lets you keep it in your format (#:##:##), but when you pass it to your custom formula, Sheets first converts it to a Javascript Date object, which your function then returns, and sheets automatically displays as a regular date (12/30/1899). See Google's warning about Date conversions with custom functions here.

The easiest solution is to just explicitly set your input format to "plain text" using the format selection dropdown, and then in your custom function code, you can parse it as you see fit.

Set input format as Plain text

For example, I used this StackOverflow answer to write your custom function:

function DURATION_DECIMALS(input){
  // https://stackoverflow.com/a/22820471/11447682
  var arr = input.split(':');
  var dec = parseInt((arr[1]/6)*10, 10);
  return parseFloat(parseInt(arr[0], 10) + '.' + (dec<10?'0':'') + dec);
}

And here it is working with format set to plain text: enter image description here

0
votes

This works for me:

function durdechrs(dt) {
  return Number((dt.valueOf()-new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf())/3600000).toFixed(2);
}