Skip to content

Commit

Permalink
Time: to integer
Browse files Browse the repository at this point in the history
  • Loading branch information
h4kuna committed Dec 18, 2023
1 parent 4c3eacc commit 2ea16b8
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 10 deletions.
36 changes: 26 additions & 10 deletions src/Date/Time.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

namespace h4kuna\DataType\Date;

use DateTime;
use DateTimeImmutable;
use DateTimeInterface;
use h4kuna\DataType\Basic\Strings;
use Nette\StaticClass;

final class Time
Expand All @@ -17,15 +17,34 @@ public static function micro(): float


/**
* @return ($dateTime is DateTimeImmutable ? DateTimeImmutable : DateTime)
* string format HH:MM[:SS]
*/
public static function only(string|DateTimeInterface $dateTime): int
{
if (is_string($dateTime)) {
$time = Strings::split($dateTime, ':');
$hour = $time[0] ?? 0;
$minute = $time[1] ?? 0;
$second = $time[2] ?? 0;
} else {
$hour = $dateTime->format('G');
$minute = $dateTime->format('i');
$second = $dateTime->format('s');
}

return ((int) $hour) * 3600
+ ((int) $minute) * 60
+ ((int) $second);
}


public static function time(
DateTime|DateTimeImmutable $dateTime,
DateTimeInterface $dateTime,
?int $hour = null,
?int $minutes = null,
?int $seconds = null,
?int $microseconds = null,
): DateTime|DateTimeImmutable
): DateTimeInterface
{
return $dateTime->setTime(
$hour ?? (int) $dateTime->format('G'),
Expand All @@ -36,15 +55,12 @@ public static function time(
}


/**
* @return ($dateTime is DateTimeImmutable ? DateTimeImmutable : DateTime)
*/
public static function date(
DateTime|DateTimeImmutable $dateTime,
DateTimeInterface $dateTime,
?int $year = null,
?int $month = null,
?int $day = null,
): DateTime|DateTimeImmutable
): DateTimeInterface
{
return $dateTime->setDate(
$year ?? (int) $dateTime->format('Y'),
Expand Down
50 changes: 50 additions & 0 deletions tests/src/Unit/Date/TimeTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php declare(strict_types=1);

namespace h4kuna\DataType\Tests\Unit\Date;

use h4kuna\DataType\Date\Time;
use Tester\Assert;
use Tester\TestCase;

require __DIR__ . '/../../../bootstrap.php';

/**
* @testCase
*/
final class TimeTest extends TestCase
{

/**
* @dataProvider provideOnly
*/
public function testOnly(int $expected, string $time): void
{
Assert::same($expected, Time::only(new \DateTime($time)));
}


/**
* @dataProvider provideOnly
*/
public function testOnlyString(int $expected, string $time): void
{
Assert::same($expected, Time::only($time));
}


/**
* @return array<mixed>
*/
protected function provideOnly(): array
{
return [
[0, 'today'],
[70215, '19:30:15'],
[25141, '6:59:01'],
[25140, '6:59'],
];
}

}

(new TimeTest())->run();

0 comments on commit 2ea16b8

Please sign in to comment.