php PHP获取一个月的周数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5853380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP get number of week for month
提问by brenjt
So I have a script that returns the number of weeks in a particular month and year. How can I take a specific day from that month and determine if it is part of week 1,2,3,4 or 5 of that month?
所以我有一个脚本可以返回特定月份和年份的周数。我如何从该月中取出特定日期并确定它是该月第 1、2、3、4 或 5 周的一部分?
回答by Marty
The most frustrating thing I have ever tried to get working - but here it is!
我曾经试图开始工作的最令人沮丧的事情 - 但它来了!
<?php
/**
* Returns the amount of weeks into the month a date is
* @param $date a YYYY-MM-DD formatted date
* @param $rollover The day on which the week rolls over
*/
function getWeeks($date, $rollover)
{
$cut = substr($date, 0, 8);
$daylen = 86400;
$timestamp = strtotime($date);
$first = strtotime($cut . "00");
$elapsed = ($timestamp - $first) / $daylen;
$weeks = 1;
for ($i = 1; $i <= $elapsed; $i++)
{
$dayfind = $cut . (strlen($i) < 2 ? '0' . $i : $i);
$daytimestamp = strtotime($dayfind);
$day = strtolower(date("l", $daytimestamp));
if($day == strtolower($rollover)) $weeks ++;
}
return $weeks;
}
//
echo getWeeks("2011-06-11", "sunday"); //outputs 2, for the second week of the month
?>
回答by Iiridayn
Edit: so much for "single line" - needed variables to avoid recomputation with the conditional. Tossed in a default argument while I was at it.
编辑:对于“单行”来说太多了 - 需要变量以避免使用条件重新计算。在我使用它时加入了默认参数。
function weekOfMonth($when = null) {
if ($when === null) $when = time();
$week = date('W', $when); // note that ISO weeks start on Monday
$firstWeekOfMonth = date('W', strtotime(date('Y-m-01', $when)));
return 1 + ($week < $firstWeekOfMonth ? $week : $week - $firstWeekOfMonth);
}
Please note that weekOfMonth(strtotime('Oct 31, 2011'));
will return 6
; some rare months have 6 weeks in them, contrary to OP's expectation. January 2017 is another month with 6 ISO weeks - Sunday the 1st falls in the last year's week, since ISO weeks start on Monday.
请注意,weekOfMonth(strtotime('Oct 31, 2011'));
将返回6
;一些罕见的月份有 6 周,这与 OP 的预期相反。2017 年 1 月又是一个有 6 个 ISO 周的月份——因为 ISO 周从星期一开始,所以是去年一周的第一个星期日。
For starshine531, to return a 0
indexed week of the month, change the return 1 +
to return 0 +
or return (int)
.
对于starshine531,要返回0
一个月的索引周,请将 更改return 1 +
为return 0 +
或return (int)
。
For Justin Stayton, for weeks starting on Sunday instead of Monday I would use strftime('%U'
instead of date('W'
, as follows:
对于Justin Stayton,从星期日而不是星期一开始的几周我将使用strftime('%U'
代替date('W'
,如下所示:
function weekOfMonth($when = null) {
if ($when === null) $when = time();
$week = strftime('%U', $when); // weeks start on Sunday
$firstWeekOfMonth = strftime('%U', strtotime(date('Y-m-01', $when)));
return 1 + ($week < $firstWeekOfMonth ? $week : $week - $firstWeekOfMonth);
}
For this version, 2017-04-30 is now in week 6 of April, while 2017-01-31 is now in week 5.
对于此版本,2017-04-30 现在是 4 月的第 6 周,而 2017-01-31 现在是第 5 周。
回答by Philip csaplar
public function getWeeks($timestamp)
{
$maxday = date("t",$timestamp);
$thismonth = getdate($timestamp);
$timeStamp = mktime(0,0,0,$thismonth['mon'],1,$thismonth['year']); //Create time stamp of the first day from the give date.
$startday = date('w',$timeStamp); //get first day of the given month
$day = $thismonth['mday'];
$weeks = 0;
$week_num = 0;
for ($i=0; $i<($maxday+$startday); $i++) {
if(($i % 7) == 0){
$weeks++;
}
if($day == ($i - $startday + 1)){
$week_num = $weeks;
}
}
return $week_num;
}
Hello all i have been struggling for the whole day trying to figure this code out, i finally figured it out so i thought i would share it with you all.
大家好,我一整天都在努力找出这段代码,我终于想通了,所以我想我会与大家分享。
all you need to do is put a time stamp into the function and it will return the week number back to you.
您需要做的就是在函数中放置一个时间戳,它会将周数返回给您。
thanks
谢谢
回答by Abhilash
there is a problem with this method. if the passing date (Lets say 2012/01/01 which is a Sunday) and "$rollover" day is "Sunday", then this function will return 2. where its actually is 1'st week. i think i have fixed it in following function. please add comments to make it better.
这种方法有问题。如果传递日期(假设 2012/01/01 是星期日)和“$rollover”日是“星期日”,那么此函数将返回 2. 它实际上是第 1 周。我想我已经在以下功能中修复了它。请添加评论以使其更好。
function getWeeks($date, $rollover)
{
$cut = substr($date, 0, 8);
$daylen = 86400;
$timestamp = strtotime($date);
$first = strtotime($cut . "01");
$elapsed = (($timestamp - $first) / $daylen)+1;
$i = 1;
$weeks = 0;
for($i==1; $i<=$elapsed; $i++)
{
$dayfind = $cut . (strlen($i) < 2 ? '0' . $i : $i);
$daytimestamp = strtotime($dayfind);
$day = strtolower(date("l", $daytimestamp));
if($day == strtolower($rollover))
{
$weeks++;
}
}
if($weeks==0)
{
$weeks++;
}
return $weeks;
}
回答by Wtower
This is a solution based on sberry's mathematical solution but using the PHP DateTimeclass instead.
这是一个基于 sberry 数学解决方案但使用 PHP DateTime类的解决方案。
function week_of_month($date) {
$first_of_month = new DateObject($date->format('Y/m/1'));
$day_of_first = $first_of_month->format('N');
$day_of_month = $date->format('j');
return floor(($day_of_first + $day_of_month - 1) / 7) + 1;
}
回答by pratik
Just Copy and Past the code and pass month and year.
只需复制并粘贴代码并传递月份和年份。
e.g month=04 year=2013.
例如月=04 年=2013。
That's exactly what You Need.
这正是您所需要的。
$mm= $_REQUEST['month'];
$yy= $_REQUEST['year'];
$startdate=date($yy."-".$mm."-01") ;
$current_date=date('Y-m-t');
$ld= cal_days_in_month(CAL_GREGORIAN, $mm, $yy);
$lastday=$yy.'-'.$mm.'-'.$ld;
$start_date = date('Y-m-d', strtotime($startdate));
$end_date = date('Y-m-d', strtotime($lastday));
$end_date1 = date('Y-m-d', strtotime($lastday." + 6 days"));
$count_week=0;
$week_array = array();
for($date = $start_date; $date <= $end_date1; $date = date('Y-m-d', strtotime($date. ' + 7 days')))
{
$getarray=getWeekDates($date, $start_date, $end_date);
echo "<br>";
$week_array[]=$getarray;
echo "\n";
$count_week++;
}
// its give the number of week for the given month and year
echo $count_week;
//print_r($week_array);
function getWeekDates($date, $start_date, $end_date)
{
$week = date('W', strtotime($date));
$year = date('Y', strtotime($date));
$from = date("Y-m-d", strtotime("{$year}-W{$week}+1"));
if($from < $start_date) $from = $start_date;
$to = date("Y-m-d", strtotime("{$year}-W{$week}-6"));
if($to > $end_date) $to = $end_date;
$array1 = array(
"ssdate" => $from,
"eedate" => $to,
);
return $array1;
// echo "Start Date-->".$from."End Date -->".$to;
}
for($i=0;$i<$count_week;$i++)
{
$start= $week_array[$i]['ssdate'];
echo "--";
$week_array[$i]['eedate'];
echo "<br>";
}
OUTPUT:
输出:
week( 0 )=>2013-03-01---2013-03-02
week( 1 )=>2013-03-03---2013-03-09
week( 2 )=>2013-03-10---2013-03-16
week( 3 )=>2013-03-17---2013-03-23
week( 4 )=>2013-03-24---2013-03-30
week( 5 )=>2013-03-31---2013-03-31
回答by rinogo
For a Monday-Sunday (ISO 8601) week (or, if you simply don't care), you can do this in one line:
对于周一至周日 (ISO 8601) 周(或者,如果您根本不在乎),您可以在一行中执行此操作:
function get_week_of_month($date) {
return date('W', $date) - date('W', strtotime(date("Y-m-01", $date))) + 1;
}
(Source)
(来源)
For anything else, (e.g. a Sunday-Saturday week), you just need to tweak $date inside the function:
对于其他任何事情(例如周日至周六),您只需要在函数内调整 $date :
function get_week_of_month($date) {
$date += 86400; //For weeks starting on Sunday
return date('W', $date) - date('W', strtotime(date("Y-m-01", $date))) + 1;
}
NOTE: You may run into some issues at the end of the year (e.g. around 12/31, 1/1, etc.). Read more here.
注意:您可能会在年底遇到一些问题(例如大约 12/31、1/1 等)。 在这里阅读更多。
回答by Mike Wright
I think I found an elegant solution
我想我找到了一个优雅的解决方案
$time = time(); // or whenever
$week_of_the_month = ceil(date('d', $time)/7);
回答by srahul07
This is the snippet that I made to fulfill my requirements for the same. Hope this will help you.
这是我为满足我的要求而制作的片段。希望这会帮助你。
function getWeek($timestamp) {
$week_year = date('W',$timestamp);
$week = 0;//date('d',$timestamp)/7;
$year = date('Y',$timestamp);
$month = date('m',$timestamp);
$day = date('d',$timestamp);
$prev_month = date('m',$timestamp) -1;
if($month != 1 ){
$last_day_prev = $year."-".$prev_month."-1";
$last_day_prev = date('t',strtotime($last_day_prev));
$week_year_last_mon = date('W',strtotime($year."-".$prev_month."-".$last_day_prev));
$week_year_first_this = date('W',strtotime($year."-".$month."-1"));
if($week_year_first_this == $week_year_last_mon){
$week_diff = 0;
}
else{
$week_diff = 1;
}
if($week_year ==1 && $month == 12 ){
// to handle December's last two days coming in first week of January
$week_year = 53;
}
$week = $week_year-$week_year_last_mon + 1 +$week_diff;
}
else{
// to handle first three days January coming in last week of December.
$week_year_first_this = date('W',strtotime($year."-01-1"));
if($week_year_first_this ==52 || $week_year_first_this ==53){
if($week_year == 52 || $week_year == 53){
$week =1;
}
else{
$week = $week_year + 1;
}
}
else{
$week = $week_year;
}
}
return $week;
}
}
回答by Trevor Arjeski
This is probably not a good way to do this but it's my first thought and I'm really tired.
这可能不是一个好方法,但这是我的第一个想法,我真的很累。
Put all your dates into an array. The date object must have a day name (Monday). Create a method that searches the array and when ever you hit a Sunday you add 1 to a week counter. Once you find the date you're looking for return the week counter. That is the week the day falls in of the year. For the week in the month you have to reset the week counter every time you get to the last day in each month.
将所有日期放入一个数组中。日期对象必须有一个日期名称(星期一)。创建一个搜索数组的方法,当您遇到星期日时,您将向周计数器加 1。找到要查找的日期后,返回周计数器。那是一年中这一天属于哪一周。对于一个月中的一周,您必须在每次到达每个月的最后一天时重置周计数器。