Subject: Re: bug#11115: linux date arithmetic

From: Eric Blake <[email-masked]>
Date: Wed, 28 Mar 2012 11:50:34 -0600

[adding bug-gnulib]

On 03/28/2012 06:39 AM, Stefan Karamuz wrote:
> Please check the 2 linux commands:
> 
> date -d "$(date +%F\ %H:%M:%S)" +%F\ %H:%M:%S
> date -d "$(date +%F\ %H:%M:%S) + 1 minute" +%F\ %H:%M:%S
> 
> It's very confusing, because the results of the two commands differ in
> one hour and one minute, except of one minute only.
> 
> [~]$ date -d "$(date +%F\ %H:%M)" +%F\ %H:%M:%S
> 2012-03-28 14:06:00
> 
> ... and after a few seconds:
> 
> [~]$ date -d "$(date +%F\ %H:%M:%S) + 1 minute" +%F\ %H:%M:%S
> 2012-03-28 15:07:20

Thanks for the report.  It's easier to debug if you use the same
starting point for both commands rather than nesting an ever-changing
$(date) to feed the outermost 'date -d', but I can indeed reproduce your
behavior, as well as explain it:

$ date -d '2012-03-28 11:38'            +%H:%M:%S
11:38:00

Starting point.

$ date -d '2012-03-28 11:38 +1'         +%H:%M:%S
04:38:00

Aha - '11:38 +1' is parsed as a time zone designation.  In my case,
since I'm in UTC-6, or 7 time zones away from UTC+1, that explains why
my output jumped backwards by 7 hours; I'm assuming your location is at
UTC+2.

$ date -d '2012-03-28 11:38 +minute'    +%H:%M:%S
11:39:00

Notice that 'minute' can be parsed without units.

$ date -d '2012-03-28 11:38 + 1 minute' +%H:%M:%S
04:39:00

Therefore, the parser is faced with an ambiguity between:

(11:38 +1) minute
11:38 (+1 minute)

and happened to choose the result you consider to be less intuitive.
But looks what happen if you rearrange the command line:

$ date -d '+1 minute 2012-03-28 11:38'  +%H:%M:%S
11:39:00

Now there is no ambiguity.

I don't know if this is something adequately explained in our FAQ:
https://www.gnu.org/software/coreutils/faq/#The-date-command-is-not-working-right_002e

nor do I know if it might be possible to patch gnulib's getdate.y to
make the parsing smarter, but you are welcome to try patching it.  In
fact, I'd go so far as to say getdate.y has a bug; '+1' is a reasonable
time zone designator when it occurs after hh:mm, but I've never seen '+
1' meant as a time zone, so it seems like the presence of space after
'+' should be used to alter the parse precedence.

So I'm not sure whether to leave this bug open (in hopes of someone
writing a patch) or to close it (since the behavior is explainable, even
if not what you wanted, and can be worked around with a little
reordering on your part).

-- 
Eric Blake   [email-masked]    +1-919-301-3266
Libvirt virtualization library http://libvirt.org