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.

9
  • possible duplicate of PHP date format converting and many, many more.... but why not use DateTime objects rather than limit yourself to strtotime()? Commented Feb 1, 2014 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') Commented Feb 1, 2014 at 18:39
  • 1
    Maybe it's the hard way, but you could checkout the source code of strtotime: github.com/php/php-src/blob/master/ext/date/php_date.c Commented Feb 1, 2014 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'. Commented Feb 1, 2014 at 18:44
  • 1
    If you're doing this for i18n, surely there's something else you could be checking. Commented Feb 1, 2014 at 19:21

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.