sia sia - 4 months ago 17
Bash Question

How to show date which is stored in variable in different timezone in shell script

I have a date that is stored in variable

myTime=$(date -d "20120101 14:13:12" +'%Y%m%d %H:%M:%S')

and I want to show it in different time zone without exporting the timezone variable. I tried this command:

c=$(TZ=":US/Eastern" date -d "$myTime" +'%Y%m%d %H:%M:%S')

but it doesn't work. can anyone tell me what is my mistake?


Timezones! It's all about timezones.

You want to store the time in your current zone, so you say

now="$(date -d '20120101 14:13:12' +'%Y%m%d %H:%M:%S')"

Now you have a date string! But wait, is that date in UTC or US/Eastern? Our zone is set to UTC, but let's look at that value...

echo "$now"
20120101 14:13:12

Funny, I don't see a zone... How can I know it's a time in UTC? Simple answer: you can't! You have to encode the zone in the string, or it's in the current zone.

You can change the zone date uses for the next run:

eastern="$(TZ=US/Eastern date -d "$now" +%Y-%m%dT%H:%M:%S)"
echo "$eastern"

But wait, isn't that just the same time? Well yes, but now it's UTC... you just can't tell that, because you didn't print the zone!

In order to convert between zones you must include the zone in your time string.

GNU date is very nice and will include this for you if you ask:

now="$(TZ=UTC date -d '20120101 14:13:12' --rfc-3339=seconds)"
echo "$now"
2012-01-01 14:13:12+00:00

Now you see your input date/time in your input zone and you know it is in the input zone because +00:00 tells you that.

Now you can go back and try to convert it:

eastern="$(TZ=US/Eastern date -d "$now" --rfc-3339=seconds)"
echo "$eastern"
2012-01-01 09:13:12-05:00

Aha! Now, because you included the zone in your input to -d and you told date to output in a different zone, the time has changed. You can now drop the zone suffix, if you really want to.