How to get date and time with different timezone?

Viewed 137

I wanted to convert GMT time to PST time and for that, I created below sample script.

set -x
sDate=2021-01-26
sTime=18:10
gt="UTC"
tz=\"America/Los_Angeles\"
CurrentDate=$(date +"%Y-%m-%d %H:%M" -d "$sDate $sTime")  
echo $CurrentDate
NewDate=$(date -d "TZ=$tz $CurrentDate" +"%Y-%m-%d %H:%M")
echo $NewDate

Output:

+ sDate=2021-01-26
+ sTime=18:10
+ gt=UTC
+ tz="America/Los_Angeles"
+ date +%Y-%m-%d %H:%M -d 2021-01-26 18:10
+ CurrentDate=2021-01-26 18:10
+ echo 2021-01-26 18:10
2021-01-26 18:10
+ date -d TZ="America/Los_Angeles" 2021-01-26 18:10 +%Y-%m-%d %H:%M
+ NewDate=2021-01-27 02:10
+ echo 2021-01-27 02:10
2021-01-27 02:10

This is the wrong output. because Greenwich Mean Time is 8 hours ahead of Pacific Standard Time and here it's ahead than GMT.

1 Answers

As per the date man pages example:

Show the local time for 9AM next Friday on the west coast of the US

          $ date --date='TZ="America/Los_Angeles" 09:00 next Fri'

In your example the NewDate variable holds the value of the date - 2021-01-26 18:10 as in America/Los Angeles converted to the local timezone GMT. The NewDate value should therefore always be greater than CurrentDate in this case.

Related