Skip to content

Commit fd7b222

Browse files
authored
Option for custom datetime format for creating object (#127)
1 parent c2f8cb7 commit fd7b222

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

docs/source/index.html.md

+1
Original file line numberDiff line numberDiff line change
@@ -444,6 +444,7 @@ result. If data of other types is encountered automatic conversion is attempted
444444

445445
Option | Type | Description
446446
------ | ---- | -----------
447+
createFromFormat | string | Custom format for creating DateTime objects from values. A format string accepted by [`DateTime::createFromFormat()`](https://www.php.net/manual/en/datetime.createfromformat.php) function.
447448
format | string | A date format string as accepted by the [`date()`](http://php.net/manual/en/function.date.php) function. Default `'c'`.
448449
nullValue | string | Raw string to display for null values. Defaults to the empty string.
449450

src/Column/DateTimeColumn.php

+14-2
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,18 @@ public function normalize($value)
2828
{
2929
if (null === $value) {
3030
return $this->options['nullValue'];
31-
} elseif (!$value instanceof \DateTimeInterface) {
32-
$value = new \DateTime((string) $value);
31+
}
32+
33+
if (!$value instanceof \DateTimeInterface) {
34+
if (!empty($this->options['createFromFormat'])) {
35+
$value = \DateTime::createFromFormat($this->options['createFromFormat'], (string) $value);
36+
if ($value === false) {
37+
$errors = \DateTime::getLastErrors();
38+
throw new \Exception(implode(', ', $errors['errors'] ?: $errors['warnings']));
39+
}
40+
} else {
41+
$value = new \DateTime((string)$value);
42+
}
3343
}
3444

3545
return $value->format($this->options['format']);
@@ -44,9 +54,11 @@ protected function configureOptions(OptionsResolver $resolver)
4454

4555
$resolver
4656
->setDefaults([
57+
'createFromFormat' => '',
4758
'format' => 'c',
4859
'nullValue' => '',
4960
])
61+
->setAllowedTypes('createFromFormat', 'string')
5062
->setAllowedTypes('format', 'string')
5163
->setAllowedTypes('nullValue', 'string')
5264
;

tests/Unit/ColumnTest.php

+11
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,17 @@ public function testDateTimeColumn()
4141
$this->assertSame('foo', $column->transform(null));
4242
}
4343

44+
public function testDateTimeColumnWithCreateFromFormat()
45+
{
46+
$column = new DateTimeColumn();
47+
$column->initialize('test', 1, [
48+
'format' => 'd.m.Y H:i:s',
49+
'createFromFormat' => 'Y-m-d\TH:i:sP',
50+
], (new DataTable($this->createMock(EventDispatcher::class)))->setName('foo'));
51+
52+
$this->assertSame('19.02.2020 22:30:34', $column->transform('2020-02-19T22:30:34+00:00'));
53+
}
54+
4455
public function testTextColumn()
4556
{
4657
$column = new TextColumn();

0 commit comments

Comments
 (0)