简体   繁体   English

在UNIX时间戳Shell / Bash中使用时区转换日期

[英]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). 我需要将日期格式为“ yyyy / mm / dd hh:mm:ss TZ”的字符串转换为UNIX时间(TZ =时区)。

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 到目前为止,我所做的是通过使用以下命令将日期格式转换为“ yyyy / mm / dd hh:mm:ss”(不带时区)

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) . 我的工作是寻找时区和日期/时间都可以如何转换为时间戳(unix时间)。 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. 例如,我需要4个变量,它们的日期/时间与dateYMD相同,但是在4个不同的时区中,以便它们的时间戳不同。

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. 您不需要两次致电date Just call it once with TZ set to the timezone you want for that variable. 只需将TZ设置为该变量所需的时区即可调用一次。

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. 您可以通过设置TZ=环境变量来做到这一点(请参阅Barmar的答案),或者将时区包括在时间字符串中。 This has higher priority than TZ=. 它的优先级高于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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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