I am trying to add hours to a given datetime in bash and its giving weird results
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
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
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
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.
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.
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.
For example if you are in UTC timezone, then following will produce correct output for you.
date -d "2020-01-21 12:00:00 UTC + 2 hour"
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.