【问题标题】:Extracting just the time for a new date仅提取新日期的时间
【发布时间】:2015-12-17 11:40:57
【问题描述】:

我在尝试处理日期和时间时非常头疼,这会占用我数小时的编程时间,因此非常感谢任何帮助。

我想做的是结合一个单独的日期和时间;区分年份和月份很容易。但是说到时间,它会输出:

Sat Dec 30 1899 14:30:00 GMT+1300 (NZDT)

表单域看起来像

时间显示正确

在纸上。

除了将整个列格式化为字符串(这会破坏项目中的其他代码)之外,我如何从中获得所需的 13:00 时间?

【问题讨论】:

    标签: javascript datetime google-apps-script google-sheets google-forms


    【解决方案1】:

    经过大量实验,我想出了一个基本的解决方案。我希望如果谷歌更新如何从表单中添加时间,它会中断。我所做的是获取时间 00:00:00 的毫秒值,并取给定时间的差值,然后使用一些简单的数学计算得出小时和分钟。

    function extractTime(date) {
    
      var milliseconds =  date.getTime()+2209203000000;
      var time = {};
      time.hours = Math.floor(milliseconds/(1000*60*60));
      time.minutes = Math.round((milliseconds/(1000*60*60)-time.hours)*60);
    
      return time;
    
    }
    

    经过测试,似乎可以工作。

    【讨论】:

      【解决方案2】:

      另一种方法:

      function getTimeFromDate(date) {
        return Utilities.formatDate(new Date(), "NZDT", "hh:mm")
      }
      

      【讨论】:

      • 哦,是的,你是对的。我什至在其他地方使用了这个功能,但由于某种原因我没有想到。我想如果您使用“NZ”作为时区,那么 DT 和 ST 将是自动的?
      【解决方案3】:

      最简单的解决方案是使用getDisplayValue() 来获取单元格显示的值,因为您不必担心 Google 表格和 Google Apps 脚本/JavaScript 处理日期时间值的方式的差异以及可能不同的时区设置Google 表格电子表格和 Google Apps 脚本项目。

      【讨论】:

        【解决方案4】:

        我遇到了同样的问题,但查看 Amit 的帖子让我意识到,确保它始终有效的最佳方法是仅使用 Google 的设置。因此,我想出了以下解决方案,无论电子表格的时区是什么(这实际上是问题的根源),它都可以工作:

        /**
         * Formats a JSON date string or a date object using the spreadsheet's timezone
         * or the timezone you specify.  Can also be found here:
         * https://gist.github.com/westc/3a90b6ad29bbd96c98603048255f8fcc
         * @param {Date|string} date
         *   The date object or the string that should be formatted as a date string.
         * @param {string=} opt_format
         *   Optional. The format of the date as it should be returned.  If not
         *   specified the format will be "yyyy-MM-dd'T'HH:mm:ss'Z'".
         * @param {string=} opt_timeZone
         *   Optional.  Timezone to use to format the date.  Defaults to the
         *   spreadsheet's time zone.
         * @return {string}
         *   The formatted version of date as a string.
         */
        function formatDate(date, opt_format, opt_timeZone) {
          return Utilities.formatDate(
            new Date(date),
            opt_timeZone || SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone(),
            opt_format || "yyyy-MM-dd'T'HH:mm:ss'Z'"
          );
        }
        

        要在工作表中找到的值上使用它,您可以按如下方式使用它:

        Logger.log(formatDate(SpreadsheetApp.getActive().getActiveCell().getValue(), "H:mm"));
        

        执行此操作后,我能够找到当前选定单元格中的时间值。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-10-30
          • 1970-01-01
          • 2013-10-06
          • 2016-02-23
          • 1970-01-01
          • 2021-10-15
          • 2016-07-27
          • 2020-10-05
          相关资源
          最近更新 更多