检测并存储各种日期格式

I have to build a PHP script that can manage an input date then convert it in a particular format (in order to save it in a MySQL database) and finally output a second date in the same format as the input.

For example :

I receive a date 2013-09-01, I convert it into 2013-09-01 00:00:00 and I store it in MySQL. Then, some days later, I have to output a new date (the input date +2 days for example) in the original format, 2013-09-03 in this case.

Input dates can be in various format such like:

2013-09-29

2013-09-01 23:20:05

2013-09-16T11:32:01+00:00

2013-09-18T13:20:02.000Z

2013-09-09T15:16:02

I think I have to detect the input date format, store it, the convert the date to the internal date storage, and finally build a new date with the original format.

My problem is that I have no idea how to detect the input date format and normalize it in order to use it later.

Does anybody have a trick for me ?

Thanks

EDIT: I don't need a solution anymore, the API service sent me an exhaustive list of input date format, so I'm going to use regex.

You can use strtotime. It's not a magical function though so it wont accept any format. For instance how do you distinguish dd-mm-yyyy vs mm-dd-yyyy? (strtotime assumes dd-mm-yyyy)

If your formats are what you gave, and you just want the date you can always just:

$date = substr($date, 0, 10);

Or is that too clever? :P

I'd strongly recommend not allowing people to put in whatever date format they want. I think it would be very difficult to determine the date or date format correctly if you're giving people free reign on how they input the date!

strtotime() can be used to convert a string to a UNIX timestamp ready to be stored - but it's not a miracle function! It won't 'tell' you what format the user entered their date in as so that it can be unravelled and shown back and it won't accept any date format.

What happens if they put in '2013-01-02', is that January 2nd or 1st Feb? How are you going to 'store' the original date format, it's not going to be possible without a lot of work and even then you couldn't exhaust all possible date formats unless you've got a lot of time on your hands.

The only reasonable way is to adapt your input form to accept only date formats that you expect, store them in the database in a standard format along with your pre-determined date formats and then show them on the page in your predetermined date formats using date() to convert it from the UNIX timestamp into something readable.