Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invalid date error in the date command linux

Tags:

date

linux

shell

In the script I am using the command

CURRENT_DATE_tmp=`date -d $CURRENT_DATE +%Y%m%d`.

It gives error date: invalid date `+%Y%m%d' what may be the reason. I know that the variable CURRENT_DATE have value in it.

like image 778
user3153014 Avatar asked Feb 16 '26 12:02

user3153014


1 Answers

date -d $CURRENT_DATE will print the date corresponding to the $CURRENT_DATE variable.

$) CURRENT_DATE="20140220"
$) date -d $CURRENT_DATE
Thu Feb 20 00:00:00 IST 2014

To store the date into a variable, try using

$) CURRENT_DATE_TMP=`date +%Y%m%d`
$) echo $CURRENT_DATE_TMP
20140704

EDIT

To print an existing date into a new format, use

$ CURRENT_DATE=`date +%Y-%m-%d`
$ echo $CURRENT_DATE 
2014-07-04
$ date -d$CURRENT_DATE "+%Y%m%d"
20140704

Better still, wrap the $CURRENT_DATE variable within quotes, so that dates with spaces don't break anything.

$ CURRENT_DATE=`date`
$ echo $CURRENT_DATE 
Fri Jul 4 17:59:45 IST 2014
$ date -d"$CURRENT_DATE" "+%Y%m%d"
20140704
$ date -d$CURRENT_DATE "+%Y%m%d"
date: extra operand ‘4’

In your current example, you have a space after the -d flag, remove it.

like image 59
Anshul Goyal Avatar answered Feb 19 '26 05:02

Anshul Goyal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!