[英]Google Spreadsheet Script - get Date as number
I have some numeric fields in my sheets that are formatted as Duration (which causes them to be treated as fractions of a day). 我的工作表中有一些数字字段,其格式设置为“持续时间”(这会将它们视为一天的一部分)。 If I use them in formulas, they are correctly treated as numbers.
如果我在公式中使用它们,它们将被正确地视为数字。
I also need to use them in a script that calculates their sum. 我还需要在计算其总和的脚本中使用它们。 But in the script, they come up as Date objects.
但是在脚本中,它们作为Date对象出现。 Is there any way to force them to come up as numbers instead?
有什么办法可以迫使他们以数字的形式出现吗? If not, how do I convert a Date into a number correctly?
如果没有,如何将日期正确转换为数字? Using
getUTCHours
/ getUTCMinutes
/ getUTCSeconds
almost works, but it truncates hours to 24, and loses precision (even if I use milliseconds, although the loss is smaller). 使用
getUTCHours
/ getUTCMinutes
/ getUTCSeconds
差不多的作品,但它截断小时至24,并失去精度(即使我用毫秒,虽然损失更小)。 The Date objects seem to have year = 1899, which is especially weird. Date对象似乎具有year = 1899,这尤其奇怪。
Currently I settled on this, but I'm not sure if it is reliable enough (the long number is getTime
for zero): 目前,我已经解决了这个问题,但是我不确定它是否足够可靠(长数字为零的
getTime
):
if (val instanceof Date) {
return (val.getTime() + 2209161600000) / 24 / 3600 / 1000;
}
Try using function cell.getDisplayValue()
. 尝试使用功能
cell.getDisplayValue()
。 It will convert time formatted cell into text, like '13:00', and then you may use 它将时间格式的单元格转换为文本,例如“ 13:00”,然后您可以使用
and plus sign to convert this into appropriate numbers: var cell = sheet.getRange(myRange); var strDisplay = cell.getDisplayValue(); var numVal = + strDisplay.substring(0, 2);
和加号将其转换为适当的数字:
var cell = sheet.getRange(myRange); var strDisplay = cell.getDisplayValue(); var numVal = + strDisplay.substring(0, 2);
var cell = sheet.getRange(myRange); var strDisplay = cell.getDisplayValue(); var numVal = + strDisplay.substring(0, 2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.