Rusty Lemur
Rusty Lemur

Reputation: 1885

BASH compute number of seconds between two timezones with daylight savings

Since the Central Timezone CDT oscillates between Central Standard Time (GMT-6) and Central Daylight Time (GMT-5), is there a way to use BASH/date to compute the number seconds between GMT and Central Time for a particular date?

For instance, calculating the number of seconds between Central Time (with DST) and GMT on March 1 should yield 6 hours * 3600 seconds/hour = 21600 seconds. Calculating it on March 31 should yield 5 hours * 3600 seconds/hour = 18000 seconds.

Upvotes: 0

Views: 56

Answers (1)

Rusty Lemur
Rusty Lemur

Reputation: 1885

Here is a solution I found.

$ date1="2018-03-11 01:59:00"

$ echo "$(TZ="US/Central"; date -d "$date1" +"%s") - $(date -u -d "$date1" +"%s")" | bc
21600

$ date1="2018-03-11 03:01:00"

$ echo "$(TZ="US/Central"; date -d "$date1" +"%s") - $(date -u -d "$date1" +"%s")" | bc
18000

It's not quite ideal since it doesn't handle an invalid date very gracefully:

$ date1="2018-03-11 02:00:00"

$ echo "$(TZ="US/Central"; date -d "$date1" +"%s") - $(date -u -d "$date1" +"%s")" | bc
date: invalid date ‘2018-03-11 02:00:00’
-1520733600

Upvotes: 1

Related Questions