Apps Script:如何自动适配BST/GMT时区格式化当前日期
Utilities.formatDate Ah, I feel your pain—dealing with daylight saving time switches messing up scheduled batch processes is such a common (and annoying) gotcha! The good news is there's a straightforward fix that eliminates the need for manual timezone adjustments.
Instead of hardcoding "GMT" as your timezone parameter, use the IANA timezone identifier for the UK: "Europe/London". This identifier is designed to automatically account for both GMT (Greenwich Mean Time) and BST (British Summer Time) transitions throughout the year.
Example Code
// This will automatically output in either GMT or BST, depending on the current date const formattedDate = Utilities.formatDate(new Date(), "Europe/London", "yyyy/MM/dd HH:mm"); console.log(formattedDate);
Why This Works
IANA timezone identifiers (like "Europe/London") are maintained to reflect official daylight saving time rules for their regions. When you use this instead of a fixed offset like "GMT", Apps Script will automatically adjust the output time to match the active timezone (GMT or BST) for the current date. No more manual tweaks or broken scheduled jobs!
Verify It's Working
If you want to confirm the timezone is switching correctly, add the timezone abbreviation to your format string:
const formattedWithTZ = Utilities.formatDate(new Date(), "Europe/London", "yyyy/MM/dd HH:mm z"); console.log(formattedWithTZ); // Will show "GMT" or "BST" alongside the time
This should replace your temporary solution with a robust, long-term fix that handles all future DST transitions automatically.
内容的提问来源于stack exchange,提问作者Malcolm Farrelle

