获取一个月的第一个或最后一个星期五 [英] Get the First or Last Friday in a Month
问题描述
我正在尝试编写这样的日历功能
function get_date($ month,$ year,$ week, $ day,$ direction)
{
....
}
$ week
是一个整数(1,2,3 ...),$ day是一天(Sun,Mon,...)或数字,以较为容易方向有点混乱,因为它有不同的计算方式。
例如,我们来调用
get_date(5,2009,1,'Sun','forward');
它使用默认值,并获得5月的第一个星期天,即2009-05-03。如果我们调用
get_date(5,2009,2,'Sun','backward');
p>
,它返回在5月的第二个最后一个星期日,即2009-05-24。
也许它可以更快...
这是非常有趣的代码。
请注意, $ direction
为1,向前为-1,为了缓解事情:)
另外, $ day
从星期一开始,值为1,星期日结束为7。
function get_date($ month,$ year,$ week,$ day,$ direction){
if($ direction> 0)
$ startday = 1 ;
else
$ startday = date('t',mktime(0,0,0,$ month,1,$ year));
$ start = mktime(0,0,0,$ month,$ startday,$ year);
$ weekday = date('N',$ start);
if($ direction * $ day> = $ direction * $ weekday)
$ offset = - $ direction * 7;
else
$ offset = 0;
$ offset + = $ direction *($ week * 7)+($ day - $ weekday);
return mktime(0,0,0,$ month,$ startday + $ offset,$ year);
}
我已经测试了几个例子,似乎总是工作,确实要仔细检查一下吧);
I'm trying to write a calendar function like this
function get_date($month, $year, $week, $day, $direction)
{
....
}
$week
is a an integer (1, 2, 3...), $day is a day (Sun, Mon, ...) or number, whichever is easier. The direction is a little confusing, because it does a different calculation.
For an example, let's call
get_date(5, 2009, 1, 'Sun', 'forward');
It uses the default, and gets the first Sunday in May ie 2009-05-03. If we call
get_date(5, 2009, 2, 'Sun', 'backward');
, it returns the second last Sunday in May ie 2009-05-24.
Perhaps it can be made quicker...
This was VERY interesting to code.
Please note that $direction
is 1 for forward and -1 for backward to ease things up :)
Also, $day
begins with a value of 1 for Monday and ends at 7 for Sunday.
function get_date($month, $year, $week, $day, $direction) {
if($direction > 0)
$startday = 1;
else
$startday = date('t', mktime(0, 0, 0, $month, 1, $year));
$start = mktime(0, 0, 0, $month, $startday, $year);
$weekday = date('N', $start);
if($direction * $day >= $direction * $weekday)
$offset = -$direction * 7;
else
$offset = 0;
$offset += $direction * ($week * 7) + ($day - $weekday);
return mktime(0, 0, 0, $month, $startday + $offset, $year);
}
I've tested it with a few examples and seems to work always, be sure to double-check it though ;)
这篇关于获取一个月的第一个或最后一个星期五的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!