How do I add X days to date and get new date?

  • I have Linux ( RH 5.3) machine

    I need to add/calculate 10 days plus date so then I will get new date (expiration date))

    for example

     # date 
     Sun Sep 11 07:59:16 IST 2012
    

    So I need to get

         NEW_expration_DATE = Sun Sep 21 07:59:16 IST 2012
    

    Please advice how to calculate the new expiration date ( with bash , ksh , or manipulate date command ?)

  • Correct answer

    8 years ago

    You can just use the -d switch and provide a date to be calculated

    date
    Sun Sep 23 08:19:56 BST 2012
    NEW_expration_DATE=$(date -d "+10 days")
    echo $NEW_expration_DATE
    Wed Oct 3 08:12:33 BST 2012 
    
      -d, --date=STRING
              display time described by STRING, not ‘now’
    

    This is quite a powerful tool as you can do things like

    date -d "Sun Sep 11 07:59:16 IST 2012+10 days"
    Fri Sep 21 03:29:16 BST 2012
    

    or

    TZ=IST date -d "Sun Sep 11 07:59:16 IST 2012+10 days"
    Fri Sep 21 07:59:16 IST 2012
    

    or

    prog_end_date=`date '+%C%y%m%d' -d "$end_date+10 days"`
    

    So if $end_date=20131001 then $prog_end_date=20131011

    Thank you!! Your examples should be in the GNU `date` info page!

    On OS X when using the build-in date you will recieve an error. Use `brew install coreutils` to install GNU's date function, `gdate`.

    doesn't work: `$ docker run -it bash bash bash-5.0# date -d "+10 days" date: invalid date '+10 days' bash-5.0# `

    @ChristianBongiorno It does work, it has worked for years if not decades. The problem is almost certainly something to do with your environment.

    `date; echo $BASH_VERSION; date -d "+10 days" Wed 13 Feb 08:03:43 GMT 2019 5.0.0(1)-release Sat 23 Feb 08:03:43 GMT 2019 `

    `bash-5.0# date; echo $BASH_VERSION; date -d "+10 days" Wed Feb 13 17:24:47 UTC 2019 5.0.2(1)-release date: invalid date '+10 days' bash-5.0# `

    @ChristianBongiorno like I said - something to do with your unnamed environment.

    There you go then - it works as expected when using the correct (coreutils) version of date.

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM