0

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

For example, the user may input date in one of the following formats:

20120121
2012-01-21
01/21/2012
01/21/2012
...

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

Here's what I've been trying, but it is not working:

echo "Please enter the date: " 
read X 
a=$X+"%y/%m/%d"
echo $a
Rubens
  • 14,478
  • 11
  • 63
  • 92
user1570210
  • 1,169
  • 12
  • 26
  • 37
  • 1
    Could this help? http://stackoverflow.com/a/1842754/16959 – Jason Sperske Jan 22 '13 at 22:30
  • Are you sure you want to handle *any* format? What if the user enters "The third weekend of the fourth decade after the first bicentennial anniversary of my parent's wedding"? – William Pursell Jan 22 '13 at 22:31
  • 3
    Agree with that link. Use the `date` command. Note that you can't convert "any" date format - Some dates are ambiguous: *eg* 01/02/2012 -- is that the 1st of feb (as I would see it), or the 2nd of january (as americans would see it) – paddy Jan 22 '13 at 22:33
  • Maybe it could pass any format that generates an exception to [Chandler](http://chandlerproject.org/) :) sorry I've been reading Dreaming in Code – Jason Sperske Jan 22 '13 at 22:33

1 Answers1

0

You can try this command:

#!/bin/bash

date='2013-01-23'
from='%Y-%m-%d'
to='%Y/%m/%d'
python -c 'import sys, datetime; print(datetime.datetime.strptime(sys.argv[1], sys.argv[2]).strftime(sys.argv[3]))' $date $from $to
kev
  • 155,172
  • 47
  • 273
  • 272