You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Google Apps Script中不依赖库获取指定时区当前时间的星期几

Get Day of Week in Specific Time Zone (Google Apps Script, No Third-Party Libraries)

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.formatDate is a built-in GAS function that takes a Date object, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 08:37:40