Linux Date Command increment giving incorrect results for leap year

date

#1

Hello,

I am calculating 6 month future date from a specific date.

I am using linux date incremental option as follows:

date "+%Y%m%d" -d "20180831 6 months"

Ideally it should give me 20190229, however the output 20190303

It seems like date incremental doesn’t count leap year logic.

Please advise.


#2

I think 2019 isn’t a leap year.

cal 02 2019
    February 2019      
Su Mo Tu We Th Fr Sa  
                1  2  
 3  4  5  6  7  8  9  
10 11 12 13 14 15 16  
17 18 19 20 21 22 23  
24 25 26 27 28    

So you are getting correct result.


#3

I agree 2019 isn’t a leap year. But I am expecting to get 20180228 instead of 20180303.
It seems like incremental function is adding 31 days without thinking which month it is.


#4

May I know your version of Linux distro and gnu coreutils? Okay, you right. I checked it manually with dateutils.dadd command:

dateutils.dadd  2018-08-31 +6m
2019-02-28

Can you install dateutils? I will now look into gnu/date.


#5

The correct command

date  +"%Y/%m/%d" -d "31 AUG 2018 + 181 days"

Always pass the –debug option to the date command:

date --debug "+%Y%m%d" -d "20180831 6 months"
date: parsed number part: (Y-M-D) 2018-08-31
date: parsed relative part: +6 month(s)
date: input timezone: system default
date: warning: using midnight as starting time: 00:00:00
date: starting date/time: '(Y-M-D) 2018-08-31 00:00:00'
date: warning: when adding relative months/years, it is recommended to specify the 15th of the months
date: after date adjustment (+0 years, +6 months, +0 days),
date:     new date/time = '(Y-M-D) 2019-03-03 00:00:00'
date: warning: month/year adjustment resulted in shifted dates:
date:      adjusted Y M D: 2018 14 31
date:    normalized Y M D: 2019 03 03
date: '(Y-M-D) 2019-03-03 00:00:00' = 1551551400 epoch-seconds
date: timezone: system default
date: final: 1551551400.000000000 (epoch-seconds)
date: final: (Y-M-D) 2019-03-02 18:30:00 (UTC)
date: final: (Y-M-D) 2019-03-03 00:00:00 (UTC+05:30)
20190303

There are many reasons why relative date calculation can go wrong (e.g. fuzzy date) see:

  1. https://www.gnu.org/software/coreutils/faq/coreutils-faq.html#The-date-command-is-not-working-right_002e
  2. https://www.gnu.org/software/coreutils/manual/html_node/Relative-items-in-date-strings.html#Relative-items-in-date-strings
  3. https://twitter.com/nixcraft/status/1042836430807097344

#6

Thank you for the reply.

Linux distribution is Redhat 6.8(santiago).


#7

actually I don’t have root privileges on this server and currently it’s not installed.

I will check with admins if they can install it.

will adding 181 days work for all scenario ? My application is looking for a generic logic to calculate 6 month future date…

Thank you for your support.