Reputation: 577
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?
Upvotes: 2
Views: 2566
Reputation: 26096
Timezones! It's all about timezones.
You want to store the time in your current zone, so you say
TZ=UTC
then="$(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 "$then"
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 "$then" +%Y-%m%dT%H:%M:%S)"
echo "$eastern"
2012-01-01T14:13:12
But wait, isn't that just the same time? Well yes, but now it's Eastern... you just can't tell that, because you didn't print the zone. The input didn't specify the zone so it was read as Eastern and then converted into the output zone, which is Eastern, and written out as Eastern with the zone omitted.
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:
then="$(TZ=UTC date -d '20120101 14:13:12' --rfc-3339=seconds)"
echo "$then"
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 "$then" --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 omit the zone in the format for the output at this step, if you really want to:
eastern="$(TZ=US/Eastern date -d "$then" '%Y-%m-%d %H:%M:%S')"
echo "$eastern"
2012-01-01 09:13:12
But you should not omit the zone because later users of the time string won't know what zone it represents.
Upvotes: 4