functions.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. }
  38. // 获取IP地址
  39. function getIpLocation($ip): string
  40. {
  41. $ip2region = new \Ip2Region();
  42. try {
  43. $region = $ip2region->memorySearch($ip);
  44. } catch (\Exception $e) {
  45. return '未知';
  46. }
  47. list($country, $number, $province, $city, $network) = explode('|', $region['region']);
  48. if ($network === '内网IP') {
  49. return $network;
  50. }
  51. if ($country == '中国') {
  52. return $province.'-'.$city.':'.$network;
  53. } else if ($country == '0') {
  54. return '未知';
  55. } else {
  56. return $country;
  57. }
  58. }