【问题标题】:Two apps script projects outputting different toLocaleTimeString() (en-US PT & Eastern)两个应用程序脚本项目输出不同的 toLocaleTimeString()(en-US PT & Eastern)
【发布时间】:2022-02-21 10:44:55
【问题描述】:

我正在为我的办公室制定时间表,但我遇到了我所期望的最后一个问题;一张表中的语言环境(用于企业的主要运营)与另一张表中的语言环境不同(将用于打卡进出)。

尽管有问题,我知道如何获得正确的时间输出,但我不知道为什么会出现问题。

我的第一张表(正确的语言环境)中的所有代码都不相关;该项目与时间和日期无关。

我的第二张工作表的代码正在做一些事情:

  1. 使用一周的开始日期和结束日期来确定要在电子表格中使用的工作表(工作表分为几周)

  2. 获取当前日期和用户名以确定打卡时间输入的位置

很简单

到目前为止,我已经尝试使用 options 将时区设置为 PT,但没有运气,我想不出任何其他会影响我的语言环境的事情。

另外,我的电脑和工作表都设置为 PT。

相关代码:

const ss = SpreadsheetApp.getActiveSpreadsheet();
const ui = SpreadsheetApp.getUi();
var index;

const dates = {
  'Today': Date.now(),
  'Feb20': Date.parse('2022-Feb-20'),
  'Feb26': Date.parse('2022-Feb-26'),
  'Feb27': Date.parse('2022-Feb-27'),
  'Mar05': Date.parse('2022-Mar-05'),
  'Mar06': Date.parse('2022-Mar-06'),
  'Mar12': Date.parse('2022-Mar-12'),
  'Mar13': Date.parse('2022-Mar-13'),
  'Mar19': Date.parse('2022-Mar-19')
}

if (dates.Feb20 < dates.Today && dates.Today < dates.Feb26) {
  index = 0;
} else if (dates.Feb27 < dates.Today && dates.Today < dates.Mar05) {
  index = 1;
} else if (dates.Mar06 < dates.Today && dates.Today < dates.Mar12) {
  index = 2;
} else if (dates.Mar13 < dates.Today && dates.Today < dates.Mar19) {
  index = 3;
} 

const sheet = ss.getSheets()[index];

const nameColumn = sheet.getRange(2, 1, 12, 1);
const dateRow = sheet.getRange(1, 2, 1, 7);

const dateOptions = {
  year: 'numeric', month: 'short', day: 'numeric', timezone: 'America/Los_Angeles'
}

const timeOptions = {
  hour: 'numeric', minute: 'numeric', second: 'numeric', timezone: 'America/Los_Angeles', hour12: false
}

function clockIn() {
  const date = new Date();
  const formattedDate = date.toLocaleDateString('en-US', dateOptions).replace(',', '').split(' ');
  Logger.log(date);
  const employeeName = ui.prompt('Enter your name: ', '', ui.ButtonSet.OK).getResponseText();
  const row = nameColumn.createTextFinder(employeeName).matchEntireCell(false).findNext().getRow() + 1;
  const col = dateRow.createTextFinder(formattedDate[2] + ' ' + formattedDate[0] + ' ' + formattedDate[1]).matchEntireCell(true).findNext().getColumn();
  sheet.getRange(row, col).setValue(new Intl.DateTimeFormat('en-US', timeOptions).format(date));
}

【问题讨论】:

  • 在清单appscript.json 文件中设置时区。
  • 或在电子表格设置中。
  • 请注意,Date.parse('2022-Feb-20') 的结果取决于实现。在 Safari 中,它会产生一个无效的日期,请参阅 Why does Date.parse give incorrect results?

标签: javascript datetime google-apps-script


【解决方案1】:

第一条评论解决了这个问题。

要解决此问题,请先在 Apps 脚本项目设置中选中以下复选框:

在编辑器中显示“appsscript.json”清单文件

然后只需将“时区”对象字面量更新为您正在使用的任何时区。

这是list of timezones

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-01
    • 2012-12-09
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-13
    相关资源
    最近更新 更多