bashdate

How to get diff between utc time and localtime in seconds?


How to get in bash diff between utc time and localtime in seconds ?


Solution

  • %s isn't trivially part of the answer without some time-related antics, epoch seconds is explicitly UTC (or maybe GMT if you're old-school), so setting TZ won't affect it.

    Similar to twalberg's suggestion:

    { read -n 1 si; IFS=":" read hh mm; } < <(date +%:z)
    echo $(( ${si}(10#$hh*3600+$mm*60) ))
    

    UPDATE: The above properly observes the signed-ness ($si) of the offset, and also uses 10#$hh since numeric literals "08" and "09" would otherwise be invalid (leading 0 implies octal).

    You can test that this is doing what you want by setting TZ for the date command:

    { read -n 1 si; IFS=":" read hh mm; } < <(TZ=Australia/Sydney date %:z)    # 39600 or 36000
    { read -n 1 si; IFS=":" read hh mm; } < <(TZ=US/Eastern date +%:z)         # -18000 or -14400
    { read -n 1 si; IFS=":" read hh mm; } < <(TZ=Canada/Newfoundland date +%:z)    # -12600 or -9000
    { read -n 1 si; IFS=":" read hh mm; } < <(TZ=US/Alaska date +%:z)         # -32400 or -28800
    

    (This isn't strictly a bash answer, since it requires GNU date or equivalent, v5.90 and later support %:z and %::z)