Skip to content

Commit

Permalink
Implement resolveUTC
Browse files Browse the repository at this point in the history
(cherry picked from commit e4089a9)
  • Loading branch information
kylekatarnls committed May 26, 2021
1 parent d3c447f commit 8d1f50f
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
24 changes: 24 additions & 0 deletions src/Carbon/Traits/Date.php
Original file line number Diff line number Diff line change
Expand Up @@ -737,6 +737,30 @@ protected function resolveCarbon($date = null)
return $date instanceof self ? $date : static::instance($date);
}

/**
* Return the Carbon instance passed through, a now instance in UTC
* if null given or parse the input if string given (using current timezone
* then switching to UTC).
*
* @param Carbon|DateTimeInterface|string|null $date
*
* @return static
*/
protected function resolveUTC($date = null): self
{
if (!$date) {
return static::now('UTC');
}

if (\is_string($date)) {
return static::parse($date, $this->getTimezone())->utc();
}

static::expectDateTime($date, ['null', 'string']);

return $date instanceof self ? $date : static::instance($date)->utc();
}

/**
* Return the Carbon instance passed through, a now instance in the same timezone
* if null given or parse the input if string given.
Expand Down
2 changes: 1 addition & 1 deletion src/Carbon/Traits/Difference.php
Original file line number Diff line number Diff line change
Expand Up @@ -638,7 +638,7 @@ public function floatDiffInRealHours($date = null, $absolute = true)
*/
public function floatDiffInRealDays($date = null, $absolute = true)
{
$date = $this->resolveCarbon($date)->utc();
$date = $this->resolveUTC($date);
$utc = $this->copy()->utc();
$hoursDiff = $utc->floatDiffInRealHours($date, $absolute);

Expand Down
7 changes: 7 additions & 0 deletions tests/Carbon/DiffTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1606,6 +1606,13 @@ public function testFloatDiff()

public function testFloatDiffWithRealUnits()
{
$from = Carbon::parse('2021-03-27 20:00 Europe/Warsaw');
$to = Carbon::parse('2021-03-27 20:00 Europe/London');
$from->floatDiffInRealDays($to);

$this->assertSame('2021-03-27 20:00:00 Europe/Warsaw', $from->format('Y-m-d H:i:s e'));
$this->assertSame('2021-03-27 20:00:00 Europe/London', $to->format('Y-m-d H:i:s e'));

date_default_timezone_set('UTC');

$this->assertSame(0.9583333333333335, Carbon::parse('2021-03-27 20:00 Europe/Warsaw')->floatDiffInRealDays('2021-03-28 20:00'));
Expand Down

0 comments on commit 8d1f50f

Please sign in to comment.