简体   繁体   English

bash中的奇怪日期行为

[英]Strange date behaviour in bash

I am trying to add hours to a given datetime in bash and its giving weird results我正在尝试在 bash 中为给定的日期时间添加小时数,并给出奇怪的结果

This is just to check if its parsing the date time correctly这只是为了检查它是否正确解析了日期时间

$ date -d "2020-01-21 12:00:00"

Tue 21 Jan 12:00:00 UTC 2020 UTC 2020 年 1 月 21 日,星期二 12:00:00

Now when I try to do date math现在当我尝试做日期数学时

$ date -d "2020-01-21 12:00:00 +2 hour"

Tue 21 Jan 11:00:00 UTC 2020 UTC 2020 年 1 月 21 日,星期二 11:00:00

I tried few other operations but similar behaviour.我尝试了一些其他操作,但行为类似。

If I change my format then it behaves correctly for eg.如果我改变我的格式,那么它的行为是正确的,例如。

date -d "12:00:00 2020-01-21 +2 hour"

Tue 21 Jan 14:00:00 UTC 2020 UTC 2020 年 1 月 21 日,星期二 14:00:00

not sure whats going on here.不知道这里发生了什么。

The +2 is being interpreted as an explicit timezone specifier (equivalent to EET), so date -d "2020-01-21 12:00:00 +2 hour" is interpreted the same as date -d "2020-01-21 12:00:00 EET hour" , which adds one hour to the timezone-adjusted time specified. +2被解释为显式时区说明符(相当于 EET),因此date -d "2020-01-21 12:00:00 +2 hour"被解释为date -d "2020-01-21 12:00:00 EET hour" ,将指定的时区调整时间增加小时。

You can either provide an explicit timezone (as suggested by Maaz) so that +2 hour is syntactically an additional offset, or you can move it to the beginning of the expression, where it can't be parsed as a timezone.您可以提供一个明确的时区(如 Maaz 所建议的),以便+2 hour在语法上是一个额外的偏移量,或者您可以将它移到表达式的开头,在那里它不能被解析为时区。

date -d "+ 2 hour 2020-01-21 12:00:00"

Basically you need to pass the timezone in command as well like UTC/CT/IST, so that date command can understand the point of reference to add extra hours.基本上,您需要在命令中传递时区以及 UTC/CT/IST,以便日期命令可以理解添加额外小时数的参考点。

For example if you are in UTC timezone, then following will produce correct output for you.例如,如果您在 UTC 时区,那么以下将为您生成正确的输出。

date -d "2020-01-21 12:00:00 UTC + 2 hour"

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

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