Skip to content

Commit

Permalink
✨ (DateHelper): 获取指定月份日期按周分组,指定日期获取周数和季度
Browse files Browse the repository at this point in the history
  • Loading branch information
Joycezhangw committed Apr 24, 2023
1 parent ed4c400 commit 9ca4e0d
Showing 1 changed file with 60 additions and 3 deletions.
63 changes: 60 additions & 3 deletions src/Helpers/DateHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@

namespace JoyceZ\LaravelLib\Helpers;

use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;

/**
* 日期常用助手函数
* Class DateHelper
Expand Down Expand Up @@ -103,8 +106,8 @@ public static function thisMonth()
public static function lastMonth()
{
$year = (int)date('Y');
$start = mktime(0, 0, 0, (int)date('m') - 1, 1,$year);
$end = mktime(23, 59, 59, (int)date('m') - 1, (int)date('t',$start), $year);
$start = mktime(0, 0, 0, (int)date('m') - 1, 1, $year);
$end = mktime(23, 59, 59, (int)date('m') - 1, (int)date('t', $start), $year);

if (date('m', $start) != date('m', $end)) {
$end -= 60 * 60 * 24;
Expand All @@ -126,7 +129,7 @@ public static function monthsAgo($month)
{
$year = (int)date('Y');
$start = mktime(0, 0, 0, (int)date('m') - $month, 1, $year);
$end = mktime(23, 59, 59, (int)date('m') - $month, (int)date('t',$start), $year);
$end = mktime(23, 59, 59, (int)date('m') - $month, (int)date('t', $start), $year);
if (date('m', $start) != date('m', $end)) {
$end -= 60 * 60 * 24;
}
Expand Down Expand Up @@ -402,4 +405,58 @@ public static function isDateTimeCross($beginTime1 = 0, $endTime1 = 0, $beginTim
}
}

/**
* 指定年月,获取日期,并按每周分组。开始时间周一至周日排序
* @param $date
* @param string $format
* @return array
* @throws \Exception
*/
public static function getWeekAMonth($date, $format = 'Y-m-d')
{
$time = strtotime($date . '-01');
$month = date('m', $time);
$carbon = new Carbon(new Carbon(date('Y-m-d', $time), 'Asia/Shanghai'));
$weeks = [];
while (intval($carbon->month) == intval($month)) {
$weeks[$carbon->weekNumberInMonth][] = $carbon->format($format);
$carbon->addDay();
}
return $weeks;
}

/**
* 指定年月,获取每周起止日期,并按每周分组
* @param $date
* @param string $format
* @return array
* @throws \Exception
*/
public static function getWeekStartEndAMoth($date, $format = 'Y-m-d')
{
$weeks = self::getWeekAMonth($date, $format);
$weekData = [];
foreach ($weeks as $key => $item) {
$weekData[$key] = [Arr::first($item), Arr::last($item)];
}
return $weekData;
}

/**
* 一个月以周一开始,为7天
* @param $timestamp 时间
* @param bool $isWeekMonday true : 一个月以周一开始,为7天;false :一个月以周日开始
* @return array
*/
public function getWeekAndQInAMonth($timestamp, $isWeekMonday = true)
{
$dt = Carbon::parse($timestamp);
$dt->timezone = "Asia/Shanghai";
return [
'week' => $isWeekMonday ? $dt->weekNumberInMonth : $dt->weekOfMonth,
'year' => $dt->year,
'quarter' => intval(($dt->month - 1) / 3 + 1)
];
}

}

0 comments on commit 9ca4e0d

Please sign in to comment.