DateHelper.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Helpers;
  4. use Carbon\Exceptions\InvalidDateException;
  5. use Illuminate\Support\Carbon;
  6. use Illuminate\Support\Str;
  7. class DateHelper
  8. {
  9. const DB_FORMAT = 'Y-MM-DD';
  10. const HUMAN_TEXT_FORMAT = 'D MMMM Y';
  11. const HUMAN_DATE_FORMAT = 'DD.MM.Y';
  12. const MINIMAL_RANDOM_YEAR = 1970;
  13. const SECONDS_IN_YEAR = 365 * 24 * 60 * 60;
  14. const YEARS = 'год|года|лет';
  15. const MONTHS = 'месяц|месяца|месяцев';
  16. const DAYS = 'день|дня|дней';
  17. /**
  18. * @param string $date
  19. * @param bool $monthAsNumber
  20. * @return string
  21. */
  22. public static function getHumanDate(string $date, bool $monthAsNumber = false): string
  23. {
  24. $format = ($monthAsNumber) ? self::HUMAN_DATE_FORMAT : self::HUMAN_TEXT_FORMAT;
  25. $dt = Carbon::parse($date);
  26. return Str::lower($dt->isoFormat($format));
  27. }
  28. /**
  29. * Случайная дата за последние X лет в формате YYYY-MM-DD
  30. * @param int|null $last_years
  31. * @return string
  32. */
  33. public static function getRandomDate(?int $last_years = 7): string
  34. {
  35. if (($last_years > ((int)date('Y') - self::MINIMAL_RANDOM_YEAR)) || ($last_years < 0)) {
  36. throw new InvalidDateException('last_years', $last_years, 1);
  37. }
  38. $seconds = rand(0, $last_years * self::SECONDS_IN_YEAR); // случайное число секунд в диапазоне от 0 до Х лет
  39. return Carbon::createFromTimestamp(strtotime('now') - $seconds)->isoFormat(self::DB_FORMAT);
  40. }
  41. /**
  42. * @param string $date
  43. * @return string
  44. */
  45. public static function getDateForDB(string $date): string
  46. {
  47. return Carbon::parse($date)->isoFormat(self::DB_FORMAT);
  48. }
  49. /**
  50. * @param string $date
  51. * @param int $months
  52. * @return string
  53. */
  54. public static function addMonths(string $date, int $months): string
  55. {
  56. return Carbon::parse($date)->addMonths($months)->isoFormat(self::DB_FORMAT);
  57. }
  58. }