Reputation: 3487
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!
Upvotes: 1
Views: 2300
Reputation: 3487
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!
Upvotes: 4
Reputation: 3961
As you alluded to, what about making a replacement Carbon class by doing something like this?
In config/app.php
<?php
'aliases' => [
// all of the aliases
'Carbon' => App\Carbon::class,
],
And then create this class:
<?php
namespace App;
use Carbon\Carbon as BaseCarbon;
class Carbon
{
public static function parse($time = null, $tz = null)
{
try {
return BaseCarbon::createFromFormat('d-m-Y', $time, $tz);
} catch (\Exception $e) {
// This will allow you to catch on when you pass a string like "tomorrow"
return BaseCarbon::parse($time, $tz);
}
}
}
Now you can do Carbon::parse('2-3-2010');
and have it be seen as 2nd of March, 2010 or Carbon::parse('tomorrow');
and have it be tomorrow.
You could figure out other ways to construct this so that the format can be specific based on user locale or something.
Upvotes: 1
Reputation: 814
Ok, so here is a code snippet that I came up with, it will accept Carbon valid strings like "tomorrow", etc. or Unix Time epochs.
$dt = is_numeric($userDate)? Carbon::createFromTimestamp((float)$userDate)
: new Carbon($userDate);
The idea is to always send a consistent format to server and do all the conversions at the client side before sending them to the server. Each language platform has tools to convert time from locale to unix epochs so that shouldn't be too hard.
Upvotes: 0