Bdfy
Bdfy

Reputation: 24709

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

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

Upvotes: 0

Views: 3237

Answers (4)

mr.spuratic
mr.spuratic

Reputation: 10127

%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)

Upvotes: 4

Otheus
Otheus

Reputation: 1052

The answer given by Mr Spuratic isn't quite correct, since the negative number is not handled properly. This affects those in Newfoundland and in Venezuela before 2016.

For the more correct variation (requiring gnu-libc, date and Bash commands published well before 2013):

utc_offset ()
{
    local z r;
    read z < <( date +%z );
    (( r= 0 ${z:0:1} ( ${z:1:2}*3600 + ${z:3:2}*60 ) ));
    echo $r
}

Examples:

TZ=US/Eastern utc_offset
-14400
(w/summer time)

TZ=Australia/Sydney utc_offset
39600

TZ=Asia/Kolkata utc_offset
19800

TZ=Canada/Newfoundland utc_offset
-9000
(not -5400 !)

Upvotes: 1

user3270657
user3270657

Reputation: 1

This will only work in places with whole hours and not minutes.

echo $(($( date +%z)*36))

Upvotes: 0

twalberg
twalberg

Reputation: 62469

You'll probably have to do a little work to get it in seconds, but date +%z will report your configured timezone offset as [+-]HHMM. Parse the output of that and do the appropriate math to figure it out in seconds.

Upvotes: 0

Related Questions