Skip to content

Commit 9ecd3c6

Browse files
committed
Catch DateTime Exception
1 parent 2b4642b commit 9ecd3c6

3 files changed

Lines changed: 14 additions & 2 deletions

File tree

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "php81_bc/strftime",
3-
"version": "0.0.6",
3+
"version": "0.0.7",
44
"description": "Locale-formatted strftime using IntlDateFormatter (PHP 8.1 compatible)",
55
"license": "MIT",
66
"authors": [

src/php-8.1-strftime.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
use DateTime;
55
use DateTimeZone;
66
use DateTimeInterface;
7+
use Exception;
78
use IntlDateFormatter;
89
use InvalidArgumentException;
910

@@ -29,7 +30,11 @@ function strftime (string $format, $timestamp = null, ?string $locale = null) :
2930
if (!($timestamp instanceof DateTimeInterface)) {
3031
$timestamp = is_int($timestamp) ? '@' . $timestamp : (string) $timestamp;
3132

32-
$timestamp = new DateTime($timestamp);
33+
try {
34+
$timestamp = new DateTime($timestamp);
35+
} catch (Exception $e) {
36+
throw new InvalidArgumentException('$timestamp argument is neither a valid UNIX timestamp, a valid date-time string or a DateTime object.', 0, $e);
37+
}
3338
}
3439

3540
$timestamp->setTimezone(new DateTimeZone(date_default_timezone_get()));

tests/strftimeTest.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
<?php
2+
declare(strict_types=1);
3+
24
use PHPUnit\Framework\TestCase;
35
use function PHP81_BC\strftime;
46

@@ -24,4 +26,9 @@ public function test_datetime_timestamp () {
2426
$result = strftime('%Y-%m-%d %H:%M:%S', new DateTime($this->str_date));
2527
$this->assertEquals('2022-03-12 01:02:03', $result);
2628
}
29+
30+
public function test_exception () {
31+
$this->expectException(InvalidArgumentException::class);
32+
$result = strftime('%Y-%m-%d %H:%M:%S', 'InvalidArgumentException');
33+
}
2734
}

0 commit comments

Comments
 (0)