pythonNinja
pythonNinja

Reputation: 499

Convert GMT with offset string to MST in bash Shell script

I have a String variable (datetime with GMT offset) in the following format. How can I convert this to a MST in bash shell script?

Input GMT :- 08/Sep/2020:11:38:01 +0000

Output MST :- 08/Sep/2020:04:38:01 -0700

We can get the offset like this

offset=$(date +%-z)

I dont want to again convert into date from string and then use offset and minus offset to reach MST.Is there a way to convert it in a better way?

Upvotes: 0

Views: 251

Answers (1)

Cyrus
Cyrus

Reputation: 88829

Convert 08/Sep/2020:11:38:01 +0000 with bash to 08 Sep 2020 11:38:01 +0000:

gmt="08/Sep/2020:11:38:01 +0000"
gmt="${gmt//\// }"                # replace all / with spaces
gmt="${gmt/:/ }"                  # replace first : with space

Then use it with GNU date:

TZ="MST" date --date="$gmt" +'%d/%h/%Y:%H:%M:%S %z'

Output:

08/Sep/2020:04:38:01 -0700

Upvotes: 2

Related Questions