説明なし

DateConverter.php 2.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace MailPoet\Util;
  3. if (!defined('ABSPATH')) exit;
  4. use MailPoetVendor\Carbon\Carbon;
  5. class DateConverter {
  6. /**
  7. * @return bool|string
  8. */
  9. public function convertDateToDatetime(string $date, string $dateFormat) {
  10. $datetime = false;
  11. if ($dateFormat === 'datetime') {
  12. $datetime = $date;
  13. } else {
  14. $parsedDate = explode('/', $date);
  15. $parsedDateFormat = explode('/', $dateFormat);
  16. $yearPosition = array_search('YYYY', $parsedDateFormat);
  17. $monthPosition = array_search('MM', $parsedDateFormat);
  18. $dayPosition = array_search('DD', $parsedDateFormat);
  19. if (count($parsedDate) === 3) {
  20. // create date from any combination of month, day and year
  21. $parsedDate = [
  22. 'year' => $parsedDate[$yearPosition],
  23. 'month' => $parsedDate[$monthPosition],
  24. 'day' => $parsedDate[$dayPosition],
  25. ];
  26. } else if (count($parsedDate) === 2) {
  27. // create date from any combination of month and year
  28. $parsedDate = [
  29. 'year' => $parsedDate[$yearPosition],
  30. 'month' => $parsedDate[$monthPosition],
  31. 'day' => '01',
  32. ];
  33. } else if ($dateFormat === 'MM' && count($parsedDate) === 1) {
  34. // create date from month
  35. if ((int)$parsedDate[$monthPosition] === 0) {
  36. $datetime = '';
  37. $parsedDate = false;
  38. } else {
  39. $parsedDate = [
  40. 'month' => $parsedDate[$monthPosition],
  41. 'day' => '01',
  42. 'year' => date('Y'),
  43. ];
  44. }
  45. } else if ($dateFormat === 'YYYY' && count($parsedDate) === 1) {
  46. // create date from year
  47. if ((int)$parsedDate[$yearPosition] === 0) {
  48. $datetime = '';
  49. $parsedDate = false;
  50. } else {
  51. $parsedDate = [
  52. 'year' => $parsedDate[$yearPosition],
  53. 'month' => '01',
  54. 'day' => '01',
  55. ];
  56. }
  57. } else {
  58. $parsedDate = false;
  59. }
  60. if ($parsedDate) {
  61. $year = $parsedDate['year'];
  62. $month = $parsedDate['month'];
  63. $day = $parsedDate['day'];
  64. // if all date parts are set to 0, date value is empty
  65. if ((int)$year === 0 && (int)$month === 0 && (int)$day === 0) {
  66. $datetime = '';
  67. } else {
  68. if ((int)$year === 0) $year = date('Y');
  69. if ((int)$month === 0) $month = date('m');
  70. if ((int)$day === 0) $day = date('d');
  71. $datetime = sprintf(
  72. '%s-%s-%s 00:00:00',
  73. $year,
  74. $month,
  75. $day
  76. );
  77. }
  78. }
  79. }
  80. if ($datetime !== false && !empty($datetime)) {
  81. try {
  82. $datetime = Carbon::parse($datetime)->toDateTimeString();
  83. } catch (\Exception $e) {
  84. $datetime = false;
  85. }
  86. }
  87. return $datetime;
  88. }
  89. }