squareetlabs /
LaravelVerifactu
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace Squareetlabs\VeriFactu\Helpers; |
||
| 6 | |||
| 7 | use DateTime; |
||
| 8 | use Exception; |
||
| 9 | |||
| 10 | class DateTimeHelper |
||
| 11 | { |
||
| 12 | /** |
||
| 13 | * Formats a DateTime object or a date/time string into ISO 8601 format. |
||
| 14 | * |
||
| 15 | * @param DateTime|string $dateTime The DateTime object or date/time string to format. |
||
| 16 | * @return string The formatted date/time string in ISO 8601 format (YYYY-MM-DDTHH:MM:SS+HH:MM). |
||
| 17 | * @throws Exception If the input is invalid or if the DateTime object cannot be created. |
||
| 18 | */ |
||
| 19 | public static function formatIso8601(DateTime|string $dateTime): string |
||
| 20 | { |
||
| 21 | if (is_string($dateTime)) { |
||
| 22 | try { |
||
| 23 | $dateTime = new DateTime($dateTime); |
||
| 24 | } catch (Exception $e) { |
||
| 25 | throw new Exception("Invalid date/time string: " . $e->getMessage()); |
||
| 26 | } |
||
| 27 | } elseif (!$dateTime instanceof DateTime) { |
||
|
0 ignored issues
–
show
introduced
by
Loading history...
|
|||
| 28 | throw new Exception("Input must be a DateTime object or a date/time string."); |
||
| 29 | } |
||
| 30 | return $dateTime->format('c'); |
||
| 31 | } |
||
| 32 | |||
| 33 | /** |
||
| 34 | * Formats a DateTime object or a date/time string as d-m-Y (e.g. 25-01-2025). |
||
| 35 | * |
||
| 36 | * @param DateTime|string $date The DateTime object or date/time string to format. |
||
| 37 | * @return string The formatted date/time string. |
||
| 38 | * @throws Exception If the input is invalid or if the DateTime object cannot be created. |
||
| 39 | */ |
||
| 40 | public static function formatDate(DateTime|string $date): string |
||
| 41 | { |
||
| 42 | if (is_string($date)) { |
||
| 43 | try { |
||
| 44 | $dateTime = new DateTime($date); |
||
| 45 | } catch (Exception $e) { |
||
| 46 | throw new Exception("Invalid date/time string: " . $e->getMessage()); |
||
| 47 | } |
||
| 48 | } elseif ($date instanceof DateTime) { |
||
|
0 ignored issues
–
show
|
|||
| 49 | $dateTime = $date; |
||
| 50 | } else { |
||
| 51 | throw new Exception("Input must be a DateTime object or a date/time string."); |
||
| 52 | } |
||
| 53 | return $dateTime->format('d-m-Y'); |
||
| 54 | } |
||
| 55 | |||
| 56 | /** |
||
| 57 | * Returns the current date and time in ISO 8601 format. |
||
| 58 | * |
||
| 59 | * @return string The current date and time in ISO 8601 format. |
||
| 60 | */ |
||
| 61 | public static function nowIso8601(): string |
||
| 62 | { |
||
| 63 | $dateTime = new DateTime(); |
||
| 64 | return $dateTime->format(DateTime::ATOM); |
||
| 65 | } |
||
| 66 | } |