在Google Apps Script中不依赖库获取指定时区当前时间的星期几
Got it, let's solve this problem cleanly using Google Apps Script's built-in tools—no external libraries needed. The issue with toLocaleString is that it returns a human-readable string which isn't great for date logic, so we'll use Utilities.formatDate instead, which lets us directly get the day of week in either numeric or string form for your target time zone.
Solution Code
Option 1: Get Numeric Day of Week
Use this if you need a number (adjust the format to match your preferred numbering system):
function getNumericDayOfWeek(timeZone) { const currentDate = new Date(); // Get ISO numeric day (1 = Monday, 7 = Sunday) const isoDayNumber = parseInt(Utilities.formatDate(currentDate, timeZone, "u")); // If you prefer 0 = Sunday, 6 = Saturday instead: // const usStyleDayNumber = (isoDayNumber % 7); return isoDayNumber; } // Example usage for Chicago time zone: console.log(getNumericDayOfWeek("America/Chicago"));
Option 2: Get String Day Name
Use this if you need a full name like "Monday" or "Friday":
function getDayName(timeZone) { const currentDate = new Date(); // "EEEE" returns the full day name (e.g., "Wednesday") // Use "EEE" for abbreviated names (e.g., "Wed") return Utilities.formatDate(currentDate, timeZone, "EEEE"); } // Example usage for Chicago time zone: console.log(getDayName("America/Chicago"));
How It Works
Utilities.formatDateis a built-in GAS function that takes aDateobject, a target time zone (using IANA time zone identifiers like "America/Chicago"), and a format string.- For numeric days: The format token
"u"gives us the ISO standard day number (1 = Monday, 7 = Sunday). If you need the US-style numbering (0 = Sunday), we adjust it with% 7. - For string names:
"EEEE"returns the full localized day name, while"EEE"gives the abbreviated version.
This approach avoids the limitations of toLocaleString because we're directly extracting the exact value we need for date logic, rather than parsing a formatted string later.
内容的提问来源于stack exchange,提问作者Alexander Soare

