使用Apps脚本比较Google表格中的日期

时间:2015-05-18 18:39:09

标签: google-apps-script google-sheets

我有一个Google Apps电子表格,其中一列包含日期时间。这张纸是通过将几张纸合并在一起而构成的。在某些行上,此值为Date(即typeof sheet.getRange(i,2).getValue()==“object”及其日期方法)。其他时间此单元格是一个数字(即typeof sheet.getRange(i,2).getValue()==“number”)但单元格格式化单元格显示为日期。

例如,2015年5月16日星期六上午9:30的日期

如果typeof firstDate ==“number”则值为42140.395833333336

如果typeof firstDate ==“object”则“valueOf”为1431783000000

此功能的目的是在每天更改时添加边框,以便每天显示在单独的单元格组中。目前,此功能是在数据类型在日期和数字之间发生变化的任何地方添加其他边框。

4

1 个答案:

答案 0 :(得分:2)

经过一些实验,我终于受到了抨击并接受了以下定义:对于数字,该值是自当地时区12/31/1899以来的天数;对于日期,.getTime()返回自1970年1月1日UTC以来的毫秒数。

因此,以下函数强制了该值:

function FixDate(dte){

  // If dte is a number then it contains a date in the form of the number of days since
  // 00:00 on 12/31/1899 in the current time zone

  if (typeof dte == "number"){
     return dte
  }

  // If dte is a date object then the getTime property contains the date as the number of
  // milliseconds since 00:00 on January 1, 1970 in GMT.  This value is converted to be
  // compatible with the other format

  return (dte.getTime() / 86400000) + 25569 - dte.getTimezoneOffset() / (60 * 24)
}
然后使用Math.floor(FixDate())查找自18/31/1899以来的日期编号。我希望能找到某种自动日期校正例程,例如工作表用来将数字格式化为日期但我找不到它。