【问题标题】:How to set current date without timestamp in google sheets using Apps Script?如何使用 Apps 脚本在谷歌表格中设置没有时间戳的当前日期?
【发布时间】:2021-02-23 11:11:00
【问题描述】:

如何在没有时间戳的情况下在 Google 表格中设置当前日期?

我正在使用以下脚本:

dateCell.setValue(new Date(new Date().setHours(0,0,0,0)));

这就是为单元格设置的内容:

2/23/2021 6:00:00

但是,当我按“Ctrl + :”在单元格中自动插入当前日期时,会插入以下内容:

2021 年 2 月 23 日

我可以使用什么脚本只设置没有时间戳的日期?

请注意,我在按下“Ctrl + :”时录制了一个宏,并生成了以下代码:

var date = new Date();
date.setHours(0, 0, 0, 0);
spreadsheet.getActiveRangeList().setValue(date)

【问题讨论】:

    标签: google-apps-script google-sheets


    【解决方案1】:

    解决方案:

    您可以使用formatDate(date, timeZone, format) 函数指定您想要的格式:

    Utilities.formatDate(new Date(), timezone, "MM/dd/yyyy");
    

    鉴于spreadsheet 已在您当前的代码中定义,这应该可以工作:

    const ss = SpreadsheetApp.getActive();
    const timezone = ss.getSpreadsheetTimeZone();
    const date = Utilities.formatDate(new Date(), timezone, "MM/dd/yyyy");
    spreadsheet.getActiveRangeList().setValue(date)
    

    最小可重现示例:

    将日期添加到单元格 A1:

    function myFunction() {
      const ss = SpreadsheetApp.getActive();
      const timezone = ss.getSpreadsheetTimeZone();
      const sh = ss.getSheetByName('Sheet1'); // put the name of your sheet
      const date = Utilities.formatDate(new Date(), timezone, "MM/dd/yyyy");
      sh.getRange('A1').setValue(date);
    }
    

    【讨论】:

      【解决方案2】:

      如果你运行循环,格式如下:

      var date = utilities.formatDate(new Date(row[3]),"GMT","dd/MMM/yyyy") 
      //row[3] is colounm number in data array where is your dates are
      

      否则没有循环:

      var date = utilities.formatDate(new Date(),"GMT","dd/MMM/yyyy")
      

      【讨论】:

        猜你喜欢
        • 2021-04-12
        • 1970-01-01
        • 1970-01-01
        • 2020-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多