DateUtil.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. class DateUtil {
  3. /**
  4. * 获取某个时间段内所有月份 (包含开头结尾月份)
  5. * @param minDate
  6. * @param maxDate
  7. * @return
  8. * @throws ParseException
  9. */
  10. public static function getMonthBetweenDates($minDate, $maxDate) {
  11. $sTime = strtotime(date('Y-m-01', strtotime($minDate)));
  12. $eTime = strtotime(date('Y-m-01', strtotime($maxDate)));
  13. $months = [];
  14. while ($sTime <= $eTime) {
  15. $months[] = date('Y-m', $sTime);
  16. $sTime = strtotime('next month', $sTime);
  17. }
  18. return $months;
  19. }
  20. /**
  21. * 获取某个时间段内所有月份 (包含开头月份,不包含结尾月份)
  22. * @param minDate
  23. * @param maxDate
  24. * @return
  25. * @throws ParseException
  26. */
  27. public static function getMonthBetweenDatesNotEnd($minDate, $maxDate) {
  28. $sTime = strtotime(date('Y-m-01', strtotime($minDate)));
  29. $eTime = strtotime(date('Y-m-01', strtotime($maxDate)));
  30. $months = [];
  31. while ($sTime < $eTime) {
  32. $months[] = date('Y-m', $sTime);
  33. $sTime = strtotime('next month', $sTime);
  34. }
  35. return $months;
  36. }
  37. /**
  38. * 获取某个时间段内所有月份 (不包含开头月份,包含结尾月份)
  39. * @param minDate
  40. * @param maxDate
  41. * @return
  42. * @throws ParseException
  43. */
  44. public static function getMonthBetweenDatesNotBegin($minDate, $maxDate) {
  45. $sTime = strtotime(date('Y-m-01', strtotime($minDate)));
  46. $eTime = strtotime(date('Y-m-01', strtotime($maxDate)));
  47. $months = [];
  48. $sTime = strtotime("next month", $sTime); //第一个月跳过
  49. while ($sTime <= $eTime) {
  50. $months[] = date('Y-m', $sTime);
  51. $sTime = strtotime('next month', $sTime);
  52. }
  53. return $months;
  54. }
  55. public static function getEveryMonthDayBetween($startTime, $endTime, $monthList) {
  56. $res = [];
  57. $min = new DateTime($startTime);
  58. $min->setTime(0, 0, 0);
  59. $max = new DateTime($endTime);
  60. $max->setTime(23, 59, 59);
  61. $curr = clone $min;
  62. while ($curr < $max) {
  63. $month = $curr->format('Y-m');
  64. if (in_array($month, $monthList)) {
  65. if (!isset($res[$month])) {
  66. $res[$month] = 0;
  67. }
  68. $res[$month] ++;
  69. }
  70. $curr->modify('+1 day');
  71. }
  72. return $res;
  73. }
  74. }