Skip to content

Commit f50c542

Browse files
authored
Add startOfHour() and endOfHour() methods to ChronosTime (#508)
Adds boundary methods to ChronosTime for resetting to hour boundaries: - startOfHour(): Resets to the start of the current hour (X:00:00.000000) - endOfHour(): Sets to the end of the current hour (X:59:59.999999)
1 parent ec9f04b commit f50c542

2 files changed

Lines changed: 61 additions & 0 deletions

File tree

src/ChronosTime.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,37 @@ public function setTime(int $hours = 0, int $minutes = 0, int $seconds = 0, int
325325
return $clone;
326326
}
327327

328+
/**
329+
* Resets time to the start of the current hour.
330+
*
331+
* @return static
332+
*/
333+
public function startOfHour(): static
334+
{
335+
$hourTicks = $this->ticks - $this->ticks % self::TICKS_PER_HOUR;
336+
337+
$clone = clone $this;
338+
$clone->ticks = $hourTicks;
339+
340+
return $clone;
341+
}
342+
343+
/**
344+
* Sets time to the end of the current hour.
345+
*
346+
* @return static
347+
*/
348+
public function endOfHour(): static
349+
{
350+
$hourTicks = $this->ticks - $this->ticks % self::TICKS_PER_HOUR;
351+
$endTicks = $hourTicks + self::TICKS_PER_HOUR - 1;
352+
353+
$clone = clone $this;
354+
$clone->ticks = $endTicks;
355+
356+
return $clone;
357+
}
358+
328359
/**
329360
* @param int $a Left side
330361
* @param int $a Right side

tests/TestCase/ChronosTimeTest.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,36 @@ public function testSetTime(): void
193193
$this->assertSame('01:00:00.000001', $t->format('H:i:s.u'));
194194
}
195195

196+
public function testStartOfHour(): void
197+
{
198+
$t = ChronosTime::parse('12:30:45.123456');
199+
$start = $t->startOfHour();
200+
201+
$this->assertNotSame($t, $start);
202+
$this->assertSame('12:00:00.000000', $start->format('H:i:s.u'));
203+
204+
$t = ChronosTime::parse('00:59:59.999999');
205+
$this->assertSame('00:00:00.000000', $t->startOfHour()->format('H:i:s.u'));
206+
207+
$t = ChronosTime::parse('23:01:01');
208+
$this->assertSame('23:00:00.000000', $t->startOfHour()->format('H:i:s.u'));
209+
}
210+
211+
public function testEndOfHour(): void
212+
{
213+
$t = ChronosTime::parse('12:30:45.123456');
214+
$end = $t->endOfHour();
215+
216+
$this->assertNotSame($t, $end);
217+
$this->assertSame('12:59:59.999999', $end->format('H:i:s.u'));
218+
219+
$t = ChronosTime::parse('00:00:00');
220+
$this->assertSame('00:59:59.999999', $t->endOfHour()->format('H:i:s.u'));
221+
222+
$t = ChronosTime::parse('23:30:00');
223+
$this->assertSame('23:59:59.999999', $t->endOfHour()->format('H:i:s.u'));
224+
}
225+
196226
public function testFormat(): void
197227
{
198228
$t = new ChronosTime('23:59:59.999999');

0 commit comments

Comments
 (0)