Timezone conversion in Bash script

bashtime zone

I found a solution about how to convert time zone with the Linux date command:
Timezone conversion by command line

$ date --date='TZ="Asia/Taipei" 18:00'
Fri Jul 16 11:00:00 BST 2010

It's working great, but I can't figure it out how to use it in a Bash script, when time is a variable, like:

TIME=18:00
DATE="`date --date='TZ="Asia/Taipei" $TIME' +%F\ %H:%M`"
echo $DATE;

I have problems with escaping special characters. And I totally don't understand why the date command works with timezones like BST, EET, etc. and not with timezones like "Asia/Taipei", Europe/Moscow, etc.

Best Answer

There's a section titled QUOTING in man bash. I suggest you read it, or the Bash Reference Manual on quoting.

A correct command line would be:

DATE=$( date --date="TZ=\"Asia/Taipei\" $TIME" +%F\ %H:%M )
  • Using $( ) prevents some quoting issues that occur with backticks.
  • You need to double-quote both the time zone (apparently for formatting reasons), and double-quote the argument to allow variable substitution, so just escape the inner quotes once.

I'm not sure what you're asking in your last paragraph, but note that the mapping from continent/city to time zone isn't bijective. Given a date and time in a time zone, you won't be able to find out what city that is. Multiple files in /usr/share/zoneinfo have the same time zone information. Additionally, it depends on when you execute the command, due to daylight savings time, areas changing their entire time zone, or other date related weirdness.

Related Question