Skip to content

Commit

Permalink
Merge pull request #34507 from kylekatarnls/feature/fallback-any-format
Browse files Browse the repository at this point in the history
[8.x] Allow modifiers in date format
  • Loading branch information
taylorotwell authored Sep 24, 2020
2 parents 9cc2622 + b084985 commit 2e38003
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Illuminate\Support\Collection as BaseCollection;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Str;
use InvalidArgumentException;
use LogicException;

trait HasAttributes
Expand Down Expand Up @@ -915,11 +916,13 @@ protected function asDateTime($value)
// Finally, we will just assume this date is in the format used by default on
// the database connection and use that format to create the Carbon object
// that is returned back out to the developers after we convert it here.
if (Date::hasFormat($value, $format)) {
return Date::createFromFormat($format, $value);
try {
$date = Date::createFromFormat($format, $value);
} catch (InvalidArgumentException $e) {
$date = false;
}

return Date::parse($value);
return $date ?: Date::parse($value);
}

/**
Expand Down
28 changes: 28 additions & 0 deletions tests/Database/DatabaseEloquentIntegrationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1413,6 +1413,34 @@ public function testTimestampsUsingOldSqlServerDateFormatFallbackToDefaultParsin
$this->assertFalse(Date::hasFormat('2017-11-14 08:23:19.734', $model->getDateFormat()));
}

public function testSpecialFormats()
{
$model = new EloquentTestUser;
$model->setDateFormat('!Y-d-m \\Y');
$model->setRawAttributes([
'updated_at' => '2017-05-11 Y',
]);

$date = $model->getAttribute('updated_at');
$this->assertSame('2017-11-05 00:00:00.000000', $date->format('Y-m-d H:i:s.u'), 'the date should respect the whole format');

$model->setDateFormat('Y d m|');
$model->setRawAttributes([
'updated_at' => '2020 11 09',
]);

$date = $model->getAttribute('updated_at');
$this->assertSame('2020-09-11 00:00:00.000000', $date->format('Y-m-d H:i:s.u'), 'the date should respect the whole format');

$model->setDateFormat('Y d m|*');
$model->setRawAttributes([
'updated_at' => '2020 11 09 foo',
]);

$date = $model->getAttribute('updated_at');
$this->assertSame('2020-09-11 00:00:00.000000', $date->format('Y-m-d H:i:s.u'), 'the date should respect the whole format');
}

public function testUpdatingChildModelTouchesParent()
{
$before = Carbon::now();
Expand Down

0 comments on commit 2e38003

Please sign in to comment.