Skip to content

Commit

Permalink
Merge pull request #2983 from briannesbitt/feature/create-from-format…
Browse files Browse the repository at this point in the history
…-integer-when-relevant

Allow integer in createFromFormat()
  • Loading branch information
kylekatarnls committed Mar 27, 2024
2 parents a6e64c7 + 9f64d55 commit 6bfea14
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/Carbon/Traits/Creator.php
Original file line number Diff line number Diff line change
Expand Up @@ -643,6 +643,19 @@ public static function createFromFormat($format, $time, $timezone = null): ?self
{
$function = static::$createFromFormatFunction;

// format is a single numeric unit
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)) {
$time = (string) $time;
}

if (!\is_string($time)) {
@trigger_error(
'createFromFormat() will only accept string or integer for 1-letter format representing a numeric unit int next version',
\E_USER_DEPRECATED,
);
$time = (string) $time;
}

if (!$function) {
return static::rawCreateFromFormat($format, $time, $timezone);
}
Expand Down
11 changes: 11 additions & 0 deletions tests/Jenssegers/DateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,20 @@ public function testMake()

public function testCreateFromCarbon()
{
// Preferred way
$date = Carbon::make(Carbon::createFromFormat('U', '1367186296'));
$this->assertInstanceOf(Carbon::class, $date);
$this->assertSame(1367186296, $date->getTimestamp());

// Accepted for backward-compatibility with some libraries
$date = Carbon::make(Carbon::createFromFormat('!U', 1367186296));
$this->assertInstanceOf(Carbon::class, $date);
$this->assertSame(1367186296, $date->getTimestamp());

// Deprecated usage
$date = Carbon::make(Carbon::createFromFormat('!md', 1225));
$this->assertInstanceOf(Carbon::class, $date);
$this->assertSame(30931200, $date->getTimestamp());
}

public function testManipulation()
Expand Down

0 comments on commit 6bfea14

Please sign in to comment.