1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of Cecil. |
5
|
|
|
* |
6
|
|
|
* (c) Arnaud Ligny <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace Cecil\Util; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Date utility class. |
18
|
|
|
* |
19
|
|
|
* This class provides utility methods for handling dates, |
20
|
|
|
* including validation, conversion to DateTime, and formatting durations. |
21
|
|
|
*/ |
22
|
|
|
class Date |
23
|
|
|
{ |
24
|
|
|
/** |
25
|
|
|
* Checks if a date is valid. |
26
|
|
|
*/ |
27
|
1 |
|
public static function isValid(string $date, string $format = 'Y-m-d'): bool |
28
|
|
|
{ |
29
|
1 |
|
$d = \DateTime::createFromFormat($format, $date); |
30
|
|
|
|
31
|
1 |
|
return $d && $d->format($format) === $date; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Date to DateTime. |
36
|
|
|
* |
37
|
|
|
* @param mixed $date |
38
|
|
|
*/ |
39
|
1 |
|
public static function toDatetime($date): \DateTime |
40
|
|
|
{ |
41
|
1 |
|
if ($date === null) { |
42
|
|
|
throw new \Exception('$date can\'t be null.'); |
43
|
|
|
} |
44
|
|
|
// DateTime |
45
|
1 |
|
if ($date instanceof \DateTime) { |
46
|
1 |
|
return $date; |
47
|
|
|
} |
48
|
|
|
// DateTimeImmutable |
49
|
1 |
|
if ($date instanceof \DateTimeImmutable) { |
50
|
1 |
|
return \DateTime::createFromImmutable($date); |
51
|
|
|
} |
52
|
|
|
// timestamp |
53
|
1 |
|
if (\is_int($date)) { |
54
|
|
|
return (new \DateTime())->setTimestamp($date); |
55
|
|
|
} |
56
|
|
|
|
57
|
1 |
|
return new \DateTime($date); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Duration in seconds to ISO 8601. |
62
|
|
|
* e.g.: '00:00:46.70' -> 'T0M46S' |
63
|
|
|
*/ |
64
|
1 |
|
public static function durationToIso8601(string $duration): string |
65
|
|
|
{ |
66
|
1 |
|
$time = new \DateTime($duration); |
67
|
1 |
|
$midnight = new \DateTime(); |
68
|
1 |
|
$midnight->setTime(0, 0); |
69
|
1 |
|
$period = $midnight->diff($time); |
70
|
|
|
|
71
|
1 |
|
return $period->format('T%iM%SS'); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|