I wanted to add one day to a date in bash using date
command. The input format of date is like this : 20130101 which means 01 January 2013
I use this command to accomplish that:
date -d "20130101 +1 day" +%Y%m%d
Everything went well till it reached this date: 20130322
and then it returned this error:
date: invalid date ‘20130322 +1 day’
I tried the code with some other similar dates, some of them were fine and some were not! Is it normal? I mean maybe it is somehow related to numeral system converting like the one that happens when a for loop reach 9th loop. How can I properly workaround the problem?
To format date in YYYY-MM-DD format, use the command date +%F or printf "%(%F)T\n" $EPOCHSECONDS . The %F option is an alias for %Y-%m-%d .
date +%S. Displays seconds [00-59] date +%N. Displays in Nanoseconds. date +%T.
Ok, I found the reason to the problem.
The problem is related to daylight saving time which is different for every time zone. So the error is expected to reproduce at different dates in respect to different time zones. More information can be found here.
My time zone is IRST (+3:30) that, for example, is adjusted to forward one hour on 22 March 2013 (20130322), so the date command returns "Invalid Date" error for this date. For solving the problem, as also mentioned in the provided link, you should provide time in addition of date, which is obviously should not be in the range of invalid time. Any time between 00:00:00 to 00:59:59 on 22 march will be invalid for my time zone and should be avoided. So for 22 March 2013 I can change the command this way to avoid the error:
date -d "20130322 12:00 +1 day" +%Y%m%d
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With