Reputation: 101
I'm working on a timesheet for my office and I've ran into the last problem I'd expect; the locale in one sheet (used for the business's main operations) is different than the locale in the other (going to be used for clocking in and out).
I know how to get the correct time output despite the problem, but I don't know why it's a problem in the first place.
None of the code in my first sheet (the correct locale) is relevant; that project has little to do with time and date.
The code for my second sheet is doing a few things:
Use the start day & end day of a week to determine which sheet to use in the spreadsheet (sheets are split into weeks)
get the current date & user's name to determine the position of the clock-in time input
Pretty simple
So far I've tried using options to set the timezone to PT, but no luck & I can't think of anything else that would affect my locale.
Also, my computer and my sheet are both set to PT.
Relevant code:
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));
}
Upvotes: 0
Views: 159
Reputation: 101
This was solved by the first comment.
To fix this issue, first check the following box in Apps Script Project Settings:
Show "appsscript.json" manifest file in editor
Then just update the "timezone" object literal to whichever timezone you're working with.
Here is a list of timezones
Upvotes: 1