Search code examples
phplaravelphp-carbon

Carbon::parse -> set default to UK format


My user enters data in a form in order to search on dates. The format of the string I receive can be as per the following examples: tomorrow, next week, last year or 01/03/2017. As you notice, by design, the input field is intended to be as flexible as possible for the user.

So anyway, the problem is that some of my users are British. Therefore, when they enter 1/3/2017 they intend to mean 1st March 2017. However, the following code:

Carbon::parse ($input);

interprets the date as 3rd Jan 2017. Before you waste your time and mine by suggesting work-arounds like Carbon::createFromFormat(), note the bit above where I note that flexibility is a key part of the functionality here.

I think what I'll probably end up doing is extending the Carbon{} class and parse() function, then swap the string with some regexp so that 1/3/2017 becomes 3/1/2017 before being processed by Carbon.

Nevertheless, perhaps some clever bod out there knows a better way of making Carbon sensitive to language/territory/region?

Many thanks!


Solution

  • When you know where to look!! http://php.net/manual/en/datetime.formats.php

    Apparently the following is true:

    $american = Carbon::parse ('1/3/2017'); // Jan 3, 2017
    $european = Carbon::parse ('1-3-2017'); // 1 March, 2017
    

    So changing slashes to dashes (or dashes to slashes) was the answer I was after!