Skip to content

Commit

Permalink
feat(human): human readable
Browse files Browse the repository at this point in the history
Adding in human readable time zones
  • Loading branch information
awjudd committed Dec 3, 2023
1 parent 04dfc2e commit 644ccd6
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 4 deletions.
22 changes: 20 additions & 2 deletions src/Timezone.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,35 @@ public function __construct(string $timezone)
}
}

public function offset()
public function offset(): int
{
return $this->timezone->getOffset(
new DateTime('now', new DateTimeZone('UTC'))
);
}

public function offsetForHumans(): string
{
$offsetSeconds = $this->offset();

$offsetHours = floor($offsetSeconds / 3600);
$offsetMinutes = floor(($offsetSeconds % 3600) / 60);

$offsetSign = ($offsetSeconds < 0) ? '-' : '+';

return sprintf(
"(GMT %s%02d:%02d) %s",
$offsetSign,
abs($offsetHours),
abs($offsetMinutes),
$this->timezone->getName()
);
}

/**
* @throws InvalidPropertyException
*/
public function __get($name)
public function __get($name): mixed
{
if (method_exists($this, $name)) {
return $this->$name();
Expand Down
24 changes: 22 additions & 2 deletions tests/TimezoneTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,14 @@ public function timezone_throws_an_exception_if_an_invalid_timezone_is_provided(
public function timezone_provides_the_correct_offset_from_utc()
{
// Arrange
$today = new \DateTime();

// Act
$subject = new Timezone('America/Toronto');

// Assert
$this->assertEquals(
-4 * 60 * 60,
( $today->format('I') === 1 ? -4 : -5) * 60 * 60,
$subject->offset()
);
}
Expand All @@ -46,13 +47,14 @@ public function timezone_provides_the_correct_offset_from_utc()
public function timezone_provides_the_correct_offset_from_utc_through_a_getter()
{
// Arrange
$today = new \DateTime();

// Act
$subject = new Timezone('America/Toronto');

// Assert
$this->assertEquals(
-4 * 60 * 60,
( $today->format('I') === 1 ? -4 : -5) * 60 * 60,
$subject->offset
);
}
Expand Down Expand Up @@ -90,4 +92,22 @@ public function timezone_returns_the_name_if_asked()
$result
);
}

/**
* @test
*/
public function timezone_returns_the_proper_offset_for_humans_text()
{
// Arrange
$subject = new Timezone('America/Halifax');

// Act
$result = $subject->offsetForHumans();

// Assert
$this->assertEquals(
'(GMT -04:00) America/Halifax',
$result
);
}
}

0 comments on commit 644ccd6

Please sign in to comment.