Search code examples
bashtimedate-arithmeticarithmetic-expressions

Addition to a Date in bash script


I wanted to add 1 hour to a date time. So I tried this -

date -u -d "2019-02-22 05:21:22 + 1 hour" +"%F %T"

And I got this as output -

2019-02-22 05:21:22

There was no addition to hours. So I played a bit more with date -

    date -u -d "2019-02-22 05:21:22 + 12 hours" +"%F %T"
    > 2019-02-21 18:21:22

    date -u -d "2019-02-22 05:21:22 - 12 hours" +"%F %T"
    > 2019-02-22 18:21:22

    date -u -d "2019-02-22 05:21:22 + 1 minutes" +"%F %T"
    > 2019-02-22 04:22:22

    date -u -d "2019-02-22 05:21:22 + 1 day" +"%F %T"
    > 2019-02-23 04:21:22

The output for each command is so confusing. I am unable to figure out how to add hours or any other time to date.

I searched online of how to use date command and went through posts like -

Most of them from above and others that I wnent thorugh have the same format to add to dates as I tried to use but it didn't work out for me.

So I would like some help in understanding how to add hours/minutes/days or any other unit of time to date and what is it that I am doing wrong.


Solution

  • parsing date time arithmetic is hard. Given:

    date -u -d "2019-02-22 05:21:22 + 1 hour" +"%F %T"
    

    date takes this part 05:21:22 + 1 hour to mean 05:21:22+0100 hour which it then interprets as 05:21:22+0100 +1 hour. Ref: https://www.gnu.org/software/coreutils/manual/html_node/Date-input-formats.html

    You can help resolve the ambiguity by putting the relative time in a different spot:

    # ............vvvvvvvv
    $ date -u -d "+ 1 hour 2019-02-22 05:21:22" +"%F %T"
    2019-02-22 06:21:22
    # .........^^
    # .......................vvvvvvvv
    $ date -u -d "2019-02-22 + 1 hour 05:21:22" +"%F %T"
    2019-02-22 06:21:22
    # .........^^
    # ................................vvvvvvvv
    $ date -u -d "2019-02-22 05:21:22 + 1 hour" +"%F %T"
    2019-02-22 05:21:22
    # .........^^
    

    Or, specify a timezone yourself

    # ...............................v
    $ date -u -d "2019-02-22 05:21:22Z + 1 hour" +"%F %T"
    2019-02-22 06:21:22
    # .........^^