|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace WebServCo\Framework\Helpers; |
|
6
|
|
|
|
|
7
|
|
|
use WebServCo\Framework\Exceptions\DateTimeException; |
|
8
|
|
|
|
|
9
|
|
|
class DateHelper |
|
10
|
|
|
{ |
|
11
|
|
|
/** |
|
12
|
|
|
* Format a date. |
|
13
|
|
|
* |
|
14
|
|
|
* Warning: Because of how \strtotime works, an invalid date will be converted to the next valid value. |
|
15
|
|
|
* If you need to validate a date, do not format it beforehand. |
|
16
|
|
|
* Use either format or validaton, but not both. |
|
17
|
|
|
*/ |
|
18
|
|
|
public static function format(string $date, string $format = 'Y-m-d'): string |
|
19
|
|
|
{ |
|
20
|
|
|
return \date($format, (int) \strtotime($date)); |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* Validate a date according to format. |
|
25
|
|
|
*/ |
|
26
|
|
|
public static function validate(string $date, string $format = 'Y-m-d'): bool |
|
27
|
|
|
{ |
|
28
|
|
|
// "!" |
|
29
|
|
|
// "Resets all fields (year, month, day, hour, minute, second, fraction and timezone information) |
|
30
|
|
|
// to zero-like values ( 0 for hour, minute, second and fraction, 1 for month and day, 1970 for year |
|
31
|
|
|
// and UTC for timezone information)" |
|
32
|
|
|
// "Without !, all fields will be set to the current date and time." |
|
33
|
|
|
$dateTime = \DateTime::createFromFormat(\sprintf('!%s', $format), $date); |
|
34
|
|
|
if (false === $dateTime) { |
|
35
|
|
|
throw new DateTimeException('Invalid date or format.'); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
// \DateTime::createFromFormat will change the original data if not valid. |
|
39
|
|
|
if ($dateTime->format($format) !== $date) { |
|
40
|
|
|
throw new DateTimeException('Invalid date.'); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
return true; |
|
44
|
|
|
} |
|
45
|
|
|
} |
|
46
|
|
|
|