Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash "date" returns "invalid date" error for a specific date string

Tags:

string

date

bash

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?

like image 922
gnome Avatar asked Oct 06 '14 08:10

gnome


People also ask

How do I get the current date in YYYY-MM-DD format in Linux?

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 .

What is date +% s in bash?

date +%S. Displays seconds [00-59] date +%N. Displays in Nanoseconds. date +%T.


1 Answers

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
like image 116
gnome Avatar answered Oct 19 '22 02:10

gnome