2

How can I convert any user inputted date into yyyy/mm/dd?

For example user can input date in one of the following formats 20120121 , 2012-01-21, 01/21/2012, 01/21/2012 etc.

But I need to convert any of the date entered by user into yyyy/mm/dd (2012/01/2012). How?

This is the script I was using , but it is not working.

echo "Please enter the date: "
read X
a=$X+"%y/%m/%d"
echo $a
2
  • Use a small perl script as suggested [here][1]. [1]: stackoverflow.com/questions/296738/…
    – michas
    Jan 22 '13 at 23:03
  • 1
    why not force the user to insert the date according to you criteria? echo "Please enter the date (YYYY/MM/DD):
    – BitsOfNix
    Jan 23 '13 at 7:05
3

here some ways, but be careful about conflicts:

[ 0:26:00 ] afsin@s15426859:~ % date --date='12/12/12'
Mi 12. Dez 00:00:00 CET 2012
[ 0:26:14 ] afsin@s15426859:~ % date --date='12/12/2012'
Mi 12. Dez 00:00:00 CET 2012
[ 0:26:24 ] afsin@s15426859:~ % date --date='2012/12/11'
Di 11. Dez 00:00:00 CET 2012
[ 0:26:37 ] afsin@s15426859:~ % date --date='2012/11/12'
Mo 12. Nov 00:00:00 CET 2012
[ 0:26:47 ] afsin@s15426859:~ % date --date='2012/11/30'
Fr 30. Nov 00:00:00 CET 2012
[ 0:27:00 ] afsin@s15426859:~ % date --date='2012-11-30'
Fr 30. Nov 00:00:00 CET 2012
[ 0:27:17 ] afsin@s15426859:~ % date --date='2012-11-12'
Mo 12. Nov 00:00:00 CET 2012
[ 0:27:24 ] afsin@s15426859:~ % date --date='2012-12-11'
Di 11. Dez 00:00:00 CET 2012

so now use in your script:

date --date=$X '+%y/%m/d'

or

a=`date --date=$X '+%y/%m/d'`
echo $a

;-)

but you must be careful about conflicts like is 11-11-12 2011-11-12 or 11.11.2012 ? This is complicated to find out what the user mean ;-))

1
  • Not all versions of date support this.
    – jordanm
    Jan 22 '13 at 23:34

This site is temporarily in read only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .