Skip to content

Commit 6bfea14

Browse files
authored
Merge pull request #2983 from briannesbitt/feature/create-from-format-integer-when-relevant
Allow integer in createFromFormat()
2 parents a6e64c7 + 9f64d55 commit 6bfea14

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

src/Carbon/Traits/Creator.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -643,6 +643,19 @@ public static function createFromFormat($format, $time, $timezone = null): ?self
643643
{
644644
$function = static::$createFromFormatFunction;
645645

646+
// format is a single numeric unit
647+
if (\is_int($time) && \in_array(ltrim($format, '!'), ['U', 'Y', 'y', 'X', 'x', 'm', 'n', 'd', 'j', 'w', 'W', 'H', 'h', 'G', 'g', 'i', 's', 'u', 'z', 'v'], true)) {
648+
$time = (string) $time;
649+
}
650+
651+
if (!\is_string($time)) {
652+
@trigger_error(
653+
'createFromFormat() will only accept string or integer for 1-letter format representing a numeric unit int next version',
654+
\E_USER_DEPRECATED,
655+
);
656+
$time = (string) $time;
657+
}
658+
646659
if (!$function) {
647660
return static::rawCreateFromFormat($format, $time, $timezone);
648661
}

tests/Jenssegers/DateTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,9 +47,20 @@ public function testMake()
4747

4848
public function testCreateFromCarbon()
4949
{
50+
// Preferred way
5051
$date = Carbon::make(Carbon::createFromFormat('U', '1367186296'));
5152
$this->assertInstanceOf(Carbon::class, $date);
5253
$this->assertSame(1367186296, $date->getTimestamp());
54+
55+
// Accepted for backward-compatibility with some libraries
56+
$date = Carbon::make(Carbon::createFromFormat('!U', 1367186296));
57+
$this->assertInstanceOf(Carbon::class, $date);
58+
$this->assertSame(1367186296, $date->getTimestamp());
59+
60+
// Deprecated usage
61+
$date = Carbon::make(Carbon::createFromFormat('!md', 1225));
62+
$this->assertInstanceOf(Carbon::class, $date);
63+
$this->assertSame(30931200, $date->getTimestamp());
5364
}
5465

5566
public function testManipulation()

0 commit comments

Comments
 (0)