简体   繁体   中英

Converting date with timezone in UNIX timestamp Shell/Bash

I need to convert a date from string in the format "yyyy/mm/dd hh:mm:ss TZ" to UNIX time (TZ = Timezone).

What I have done so far is to convert a date in the format "yyyy/mm/dd hh:mm:ss" without a timezone to timestamp by using

dateYMD="2019/2/28 12:23:11.46"
newt=$(date -d "${dateYMD}" +"%s")
echo ${newt}

and I have the following result.

1551349391

My struggle is to find how both timezone and date/time can be converted to timestamp (unix time) . For example I need 4 variables with the same date/time as dateYMD but in 4 different timezones so that their timestamps would be different.

Here is the latest I have tried

dateYMD="2017/09/09 08:58:09"
timez=$(TZ=Australia/Sydney date -d @$(date +%s -d "${dateYMD}"))
unixTimez=$( date --date "${timez}" +"%s" )
echo ${unixTimez}

that showed me the following error

   date: invalid date ‘чт фев 28 21:23:11 AEDT 2019’

You don't need to call date twice. Just call it once with TZ set to the timezone you want for that variable.

timesydney=$(TZ=Australia/Sydney date -d "$dateYMD" +%s)
timenyc=$(TZ=US/Eastern date -d "$dateYMD" +%s)

Either you do it by setting the TZ= environment variable (see answer of Barmar), or you include the time zone into the time string. This has higher priority than TZ=.

Examples:

TZ=UTC date -d '2019-01-01 12:00 CET' +'%s, %F %T %Z %z'
TZ=CET date -d '2019-01-01 12:00 CET' +'%s, %F %T %Z %z'
TZ=UTC date -d '2019-01-01 12:00 PDT' +'%s, %F %T %Z %z'
TZ=CET date -d '2019-01-01 12:00 PDT' +'%s, %F %T %Z %z'
TZ=UTC date -d '2019-01-01 12:00 +500' +'%s, %F %T %Z %z'

will print

1546340400, 2019-01-01 11:00:00 UTC +0000
1546340400, 2019-01-01 12:00:00 CET +0100
1546369200, 2019-01-01 19:00:00 UTC +0000
1546369200, 2019-01-01 20:00:00 CET +0100
1546326000, 2019-01-01 07:00:00 UTC +0000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM