简体   繁体   中英

Getting an error parsing data in google sheet custom script function

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?

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.

将输入格式设置为纯文本

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: 在此处输入图片说明

This works for me:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM