From the Unix command line, how do I convert a date string in the format MMDDYYYY to the format YYYY-MM-DD? For instance, how do I convert 02032017 to 2017-02-03? Thanks!
I have tried this, but I'm afraid it did not work.
date -d "02032017"
This produces this error message.
date: invalid date ‘02032017’
String manipulation with variable expansions
input_date=02032017
output_date=${input_date:4}-${input_date::2}-${input_date:2:2}
This should work,
DATE="02032017"; date -d"$DATE" +%Y-%m-%d
Error in the above answer.
Try this one
month=$(cut -c 1-2)
date=$(cut -c 3-4)
year=$(cut -c 5-8)
date=$year-$month-$date
echo $date
You can use a date library that allows you to specify the incoming date's format, for example perl's Time::Piece :
input_date=02032017
perl -MTime::Piece -sE 'say Time::Piece->strptime($date, "%m%d%Y")->ymd' -- -date="$input_date"
2017-02-03
This should also work
date="02032017"
year=${date:4:4}
month=${date:0:2}
day=${date:2:2}
formatted_date=$year-$month-$day
echo $formatted_date
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.