我正在尝试编写这样的日历函数
function get_date($month, $year, $week, $day, $direction)
{
....
}
Run Code Online (Sandbox Code Playgroud)
$week是一个整数(1,2,3 ......),$ day是一天(太阳,周一,......)或数字,以较容易的为准.方向有点混乱,因为它做了不同的计算.
举个例子,我们来电
get_date(5, 2009, 1, 'Sun', 'forward');
它使用默认值,并获得5月的第一个星期日,即2009-05-03.如果我们打电话
get_date(5, 2009, 2, 'Sun', 'backward');
,它返回五月的最后一个星期日,即2009-05-24.
我正在使用以下代码:
public static function getDays($day, $m, $y) {
$days = new DatePeriod(
new DateTime("first $day of $m $y"),
DateInterval::createFromDateString('next ' . $day),
new DateTime("last day of $m $y")
);
foreach ($days as $day) {
$dates[] = $day->format("Y-m-d");
}
return $dates;
}
Run Code Online (Sandbox Code Playgroud)
它在很大程度上起作用.我给它一个范围,它返回我在范围内的每一天的日期.
用法:
foreach(General::getDays('friday',$this->_uri[2],$this->_uri[3]) as $date) {
var_dump($date);
}
Run Code Online (Sandbox Code Playgroud)
2013年7月,这将在2013年7月的所有星期五返回正确的4个结果:
string '2013-07-05' (length=10)
string '2013-07-12' (length=10)
string '2013-07-19' (length=10)
string '2013-07-26' (length=10)
Run Code Online (Sandbox Code Playgroud)
但是,在最后一天与我所追踪的日期(例如,2013年5月和2014年1月的星期五)相匹配的一个月,它错过了返回结果中的月份的最后一天.
2013年5月的结果,当然缺少星期五的第31天:
string '2013-05-03' (length=10)
string '2013-05-10' (length=10)
string '2013-05-17' (length=10)
string '2013-05-24' (length=10)
Run Code Online (Sandbox Code Playgroud)
有没有人有这个答案?这是我错过使用DateInterval还是本课程中的真正错误?
我有个问题,
$fridays = array();
$fridays[0] = date('Y-m-d', strtotime('first friday of this month'));
$fridays[1] = date('Y-m-d', strtotime('second friday of this month'));
$fridays[2] = date('Y-m-d', strtotime('third friday of this month'));
$fridays[3] = date('Y-m-d', strtotime('fourth friday of this month'));
$fridays[4] = date('Y-m-d', strtotime('fifth friday of this month'));
Run Code Online (Sandbox Code Playgroud)
但周五没有第五个星期五.几个月有五个星期五.如何检查并不设置最后一项数组?