How to get the hour difference between two time zones in bash

Bo Berglund bo.berglund at gmail.com
Tue Mar 29 07:49:25 UTC 2022


On Mon, 28 Mar 2022 12:41:01 -0800, "Bob" <ubuntu-qygzanxc at listemail.net> wrote:

>> So I need to calculate on the start of the script which is the current number of
>> hours difference between Stockholm and New York.
>> 
>> How can this be done?
>
>I have done that in the past.  You need to know the TZ parameters for each time
>zone.  That will give you the start and end of daylight time and the hours
>difference from UTC.  Compute UTC from local time for each zone and subtract
>the difference and if needed convert back to local time from UTC.

So I figured it out now:

#!/bin/bash
TIMSWE=$(date "+%H")
export TZ=America/New_York
TIMUS=$(date "+%H")
export TZ=Europe/Stockholm
TIMDIFF=$(($TIMSWE - $TIMUS))
echo "HourSwe=$TIMSWE"
echo "HourUsa=$TIMUS"
echo "TimeDiff=$TIMDIFF"

When I run it:

$ ./testscript.sh
HourSwe=21
HourUsa=15
TimeDiff=6

So I can use this to figure out the "time distance" this way and use it in my
script to select the needed actions.


-- 
Bo Berglund
Developer in Sweden





More information about the ubuntu-users mailing list