4

Is it possible to get the format of a formatted date string in PHP?

For example,

Input: 2014-02-01
Output: Y-m-d

Input: February 1, 2014
Output: F j, Y

I understand that there will be problem with relative dates like tomorrow or 'next monday'. So, input will be a complete date string in a format that is accepted by strtotime.

Joyce Babu
  • 19,602
  • 13
  • 62
  • 97
  • possible duplicate of [PHP date format converting](http://stackoverflow.com/questions/2332740/php-date-format-converting) and many, many more.... but why not use DateTime objects rather than limit yourself to strtotime()? – Mark Baker Feb 01 '14 at 18:36
  • 2
    No, it is not. In the other question, he want to parse the date in the specified format (which he already knows). I want the format in which the date is parsed automatically by strtotime. In simple words, he is expecting a datetime, whereas I expect a date format string (like 'Y-m-d') – Joyce Babu Feb 01 '14 at 18:39
  • 1
    Maybe it's the hard way, but you could checkout the source code of `strtotime`: https://github.com/php/php-src/blob/master/ext/date/php_date.c – Marcos Feb 01 '14 at 18:44
  • 4
    This is pretty much impossible by definition for arbitrary input; e.g. what is `01/02/03`? I think the best you can do is prepare a bunch of regexen of expected input with maps to output, e.g. `/^\d{4}-\d{2}-\d{2}$/` → 'Y-m-d'. – deceze Feb 01 '14 at 18:44
  • @enrmarc - I am looking for a php only solution. Thank. – Joyce Babu Feb 01 '14 at 18:49
  • @deceze - The problem is that there is too many possible combinations. I will try partial matches, instead of the whole string. Thanks. – Joyce Babu Feb 01 '14 at 18:52
  • 1
    If you're doing this for i18n, surely there's something else you could be checking. – Rob W Feb 01 '14 at 19:21
  • how can you know that 2014-02-01 is y-m-d and not y-d-m ? – Dima Feb 01 '14 at 21:26
  • possible duplicate of [Get date format like "Y-m-d H:i:s" from a php date](http://stackoverflow.com/questions/1855304/get-date-format-like-y-m-d-his-from-a-php-date) -- Only the accepted answer will help you, though. – Potherca Feb 02 '14 at 21:11

1 Answers1

0

As answered elsewhere on StackOverflow there is no clear cut way to do this. You would have to create regular expressions for all the formats you want to support.

Depending on the formats you support, this will run into trouble with different internationalization scenarios, as pointed out in the comments to your question and the answer to this question:

you can't do much about ambiguous dates like 2nd of March 2009, which could be represented as 09/03/02, 2009-03-02, 02/03/09, 03/02/09, or even 09/02/03.

Community
  • 1
  • 1
Potherca
  • 13,207
  • 5
  • 76
  • 94