Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions src/ChronosTime.php
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,37 @@ public function setTime(int $hours = 0, int $minutes = 0, int $seconds = 0, int
return $clone;
}

/**
* Resets time to the start of the current hour.
*
* @return static
*/
public function startOfHour(): static
{
$hourTicks = $this->ticks - $this->ticks % self::TICKS_PER_HOUR;

$clone = clone $this;
$clone->ticks = $hourTicks;

return $clone;
}

/**
* Sets time to the end of the current hour.
*
* @return static
*/
public function endOfHour(): static
{
$hourTicks = $this->ticks - $this->ticks % self::TICKS_PER_HOUR;
$endTicks = $hourTicks + self::TICKS_PER_HOUR - 1;

$clone = clone $this;
$clone->ticks = $endTicks;

return $clone;
}

/**
* @param int $a Left side
* @param int $a Right side
Expand Down
30 changes: 30 additions & 0 deletions tests/TestCase/ChronosTimeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,36 @@ public function testSetTime(): void
$this->assertSame('01:00:00.000001', $t->format('H:i:s.u'));
}

public function testStartOfHour(): void
{
$t = ChronosTime::parse('12:30:45.123456');
$start = $t->startOfHour();

$this->assertNotSame($t, $start);
$this->assertSame('12:00:00.000000', $start->format('H:i:s.u'));

$t = ChronosTime::parse('00:59:59.999999');
$this->assertSame('00:00:00.000000', $t->startOfHour()->format('H:i:s.u'));

$t = ChronosTime::parse('23:01:01');
$this->assertSame('23:00:00.000000', $t->startOfHour()->format('H:i:s.u'));
}

public function testEndOfHour(): void
{
$t = ChronosTime::parse('12:30:45.123456');
$end = $t->endOfHour();

$this->assertNotSame($t, $end);
$this->assertSame('12:59:59.999999', $end->format('H:i:s.u'));

$t = ChronosTime::parse('00:00:00');
$this->assertSame('00:59:59.999999', $t->endOfHour()->format('H:i:s.u'));

$t = ChronosTime::parse('23:30:00');
$this->assertSame('23:59:59.999999', $t->endOfHour()->format('H:i:s.u'));
}

public function testFormat(): void
{
$t = new ChronosTime('23:59:59.999999');
Expand Down
Loading