如何用Bash提取指定日期时间的UTC偏移量(非当前本地时间)
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:
Explicit Timezone (Recommended)
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
%zformat specifier works across both GNU and BSDdate(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
-0600instead.
内容的提问来源于stack exchange,提问作者quanta

