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

如何用Bash提取指定日期时间的UTC偏移量(非当前本地时间)

Get UTC Offset for a Specific Past Date in Local Timezone

Got it, I totally get what you're asking for—you don't need the current UTC offset from date +%z or date -R, but a way to calculate the offset for any arbitrary past date/time in your local timezone (like Chicago in your example). Let's break down how to do this with standard tools:

For GNU Date (Most Linux Systems)

GNU date makes this straightforward with the -d flag, which lets you parse a specific date/time string. You can either rely on your system's default timezone (if it's already set to Chicago) or explicitly specify the timezone to avoid ambiguity:

This ensures you're always parsing the date in the correct timezone, regardless of system settings:

date -d "2018-04-01 12:33:45 America/Chicago" +%z

For your example, this will return -0500—since April in Chicago is Daylight Saving Time (CDT), which is UTC-5.

Simplified (If System Timezone is Chicago)

If your system is already configured to use the Chicago timezone, you can skip the explicit timezone:

date -d "2018-04-01 12:33:45" +%z

More Readable Offset Format

If you prefer the offset with a colon (like -05:00 instead of -0500), use the %:z format specifier:

date -d "2018-04-01 12:33:45 America/Chicago" +%:z

For BSD Date (macOS, FreeBSD)

BSD date uses slightly different syntax. You'll need the -j flag (to avoid setting the system clock) and -f to define the input date format. Again, you can set the timezone temporarily with the TZ environment variable:

TZ="America/Chicago" date -j -f "%Y-%m-%d %H:%M:%S" "2018-04-01 12:33:45" +%z

This will output the same -0500 for your example date.

Key Notes

  • The %z format specifier works across both GNU and BSD date (though the command syntax to parse the input date differs).
  • Always specify the timezone explicitly if your system's default might change, or if you're writing scripts that need to be portable.
  • This method automatically accounts for Daylight Saving Time changes—so if you test a date in January (Chicago's Central Standard Time, UTC-6), it'll return -0600 instead.

内容的提问来源于stack exchange,提问作者quanta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:04:53