Jan van den Berg
Jan van den Berg

Reputation: 45

Adding days to GNU date command with time stamp

When I run this command I get what you'd expect:

date -d "2018-06-07 + 1 days"
Fri Jun  8 00:00:00 CEST 2018

1 day is added to the day provided (using midnight as starting point).

However when I try to work in a time (17:00:00), two things happen.

date -d "2018-06-07 17:00:00 + 28 days" 
  1. Up to 25 days, the output is wrong: wrong dates/wrong time (I have run this in a loop).
  2. Above 25 days, it starts spitting out "date: invalid date ‘2018-06-07 17:00:00 +25 days’"

The manpage says about -d /--date that is pretty much free format. But I'm starting to think the plus sign is incorrectly interpreted (maybe as a timezone offset?) when you use the time (hours:minutes:seconds)?

So how can I add days FROM a timestamped date?

Upvotes: 2

Views: 604

Answers (1)

Inian
Inian

Reputation: 85560

For increment on the days with timestamp to work, the timestamp needs to be in the standard format returned by default by the date command. So sanitize the date to a format in which it accepts minute arithmetic and do the processing.

date -d "2018-06-07 17:00:00"
Thu, Jun 07, 2018  5:00:00 PM

Now put it in a variable, e.g. putting your string in the example below

dateStr=$(date -d "2018-06-07 17:00:00")
date -d "$dateStr + 28 days"

returns

Thu, Jul 05, 2018  5:00:00 PM

The example uses timezones from IST.

Upvotes: 2

Related Questions