Linux – convert timezone of timestamp string in bash

bashlinux

I have a date/time string which is extracted from a filename. I know that the timestamp was written using time zone A and I need to convert it to time zone B for further processing. Is this possible in bash?

eg:

filenameTimestamp="2015-01-20 18:05:02"
timezoneA="Australia/Sydney"
timezoneB="Australia/Brisbane"

I assume I will have to parse the string using time zone A and then output it again to a string using time zone B.

Best Answer

To interpret the date in Sydney to a date in Los Angeles, USA:

$ sec=$(TZ="Australia/Sydney" date +'%s' -d "2015-05-20 18:05:02")
$ TZ="America/Los_Angeles" date -d "@$sec"
Wed May 20 01:05:02 PDT 2015

Here is the result for Brisbane:

$ TZ="Australia/Brisbane" date -d "@$sec"
Wed May 20 18:05:02 AEST 2015

How it works

  • TZ="Australia/Sydney" date +'%s' -d "2015-05-20 18:05:02"

    This temporarily sets the timezone to Sydney and converts the date "2015-05-20 18:05:02" to time in seconds since epoch (UTC).

  • sec=$(TZ="Australia/Sydney" date +'%s' -d "2015-05-20 18:05:02")

    This saves the time in seconds since epoch (UTC) into the shell variable sec.

  • TZ="America/Los_Angeles" date -d "@$sec"

    This temporarily sets the timezone to Los Angeles and interprets the the date given by sec.

Related Question