functions.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. /**
  3. * Here is your custom functions.
  4. */
  5. // 验证日期格式是否有问题
  6. function isValidDate($date, $format = 'Y-m-d'): bool
  7. {
  8. $d = DateTime::createFromFormat($format, $date);
  9. return $d && $d->format($format) === $date;
  10. }
  11. /**
  12. * 获取两个日期之间的所有月份(格式:202508)
  13. *
  14. * @param string $startDate 开始日期(格式:Y-m-d)
  15. * @param string $endDate 结束日期(格式:Y-m-d)
  16. * @return array 月份数组,格式为 ['202508', '202509', ...]
  17. */
  18. function getMonthsBetweenDates($startDate, $endDate) {
  19. $months = [];
  20. // 转换为 DateTime 对象
  21. $start = new DateTime($startDate);
  22. $end = new DateTime($endDate);
  23. // 确保开始日期不大于结束日期
  24. if ($start > $end) {
  25. return $months;
  26. }
  27. // 设置开始日期为当月的第一天
  28. $start->modify('first day of this month');
  29. // 循环直到超过结束日期
  30. while ($start <= $end) {
  31. // 添加当前月份到数组(格式:202508)
  32. $months[] = $start->format('Ym');
  33. // 增加一个月
  34. $start->add(new DateInterval('P1M'));
  35. }
  36. return $months;
  37. }