[英]Carbon get number of days in actual month and week
I am trying to collect all the current days of the week and of the month in an array.我正在尝试将一周中的所有当前天数和本月的所有当前天数收集到一个数组中。 It should be easy, but as much as I search, I can't find a solution.
这应该很容易,但是尽管我搜索了很多,但我找不到解决方案。 For example putting today as the day, the result I need is something like this:
例如把今天作为一天,我需要的结果是这样的:
$daysInWeek = [31,1,2,3,4,5,6];
$daysInMonth = [1,2,3,4,5,6,7,...,28];//Note here that are febrary, and need to return 28, not 31
I write this code, But I think that Carbon can make it easier:我写了这段代码,但我认为 Carbon 可以使它更容易:
$weekStartDate = Carbon::now()->startOfWeek();
$monthStartDate = Carbon::now()->startOfMonth();
$daysInWeek[] = $weekStartDate->day;
for ($i=0; $i < 6; $i++) {
$daysInWeek[] = $weekStartDate->addDay(1)->day;
}
$daysInMonth[] = $monthStartDate->day;
$lastMonthDay = Carbon::now()->month()->daysInMonth; //This return 31 days, not 28.
for ($i=0; $i < $lastMonthDay-1; $i++) {
$daysInMonth[] = $monthStartDate->addDay(1)->day;
}
calculating days based on week number, check here Calculating days of week given a week number根据周数计算天数,请在此处查看给定周数的情况下计算一周中的天数
getting the numbers of days by months is even easier with date_create
and date_diff
function使用
date_create
和date_diff
function 更容易按月获取天数
for ex:例如:
<?php
$d1 = date_create(date('Y').'-'.date('m').'-01'); //current month/year
$d2 = date_create($d1->format('Y-m-t')); //get last date of the month
$days = date_diff($d1,$d2);
echo "Number of days: ". $days->days+1; //+1 for the first day
knowing the numbers of days, u can now create the necessary array for ex:知道天数后,您现在可以为 ex 创建必要的数组:
<?php
$days_arr = [];
$d = 1;
do{
$days_arr[] = $d;
$d++;
}while ($d <= $days->days+1);
print_r($days_arr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.