Sunil
Sunil

Reputation: 180

shell script to get year, date and month from YYYY-MM-DD format

I am running a shell script which accepts date in "YYYY-MM-DD" format. from this date input, how can i get year, month and day separately?

Thanks for replies in advance.

Upvotes: 4

Views: 21647

Answers (4)

Kar.ma
Kar.ma

Reputation: 857

I didn't want to use date command, so I got the following code. It uses awk, which I feel is more appropriate for this task. I assumed you want to store results in variables.

inputDate=2017-07-06

year=`echo $inputDate | awk -F\- '{print $1}'`
month=`echo $inputDate | awk -F\- '{print $2}'`
day=`echo $inputDate | awk -F\- '{print $3}'`

Upvotes: 1

konsolebox
konsolebox

Reputation: 75568

You could do this to store them on variables with one command:

read YEAR MONTH DAY < <(date -d '2013-09-06' '+%Y %m %d')
printf "%s\n" "$YEAR" "$MONTH" "$DAY"

Upvotes: 2

blackSmith
blackSmith

Reputation: 3154

Try this :

dt="2011-2-3"
arr=( $( date --date=$dt "+%Y  %m  %d") )
echo "Year > $arr"
echo "Month > ${arr[1]}"
echo "Month > ${arr[2]}"

Upvotes: 0

Kent
Kent

Reputation: 195209

except for processing the string as text(with grep/sed/awk/cut/...), you could do with with date command:

kent$  date -d '2013-09-06' +%Y
2013

kent$  date -d '2013-09-06' +%m
09

kent$  date -d '2013-09-06' +%d
06

Upvotes: 10

Related Questions