通过循环使用周数和月份来获取日期?

时间:2013-09-20 07:11:18

标签: php date

我很担心通过提供一个月的一个星期和一天的多月来从函数中获取日期,

喜欢,

$date = new DateTime();
        $event->event_date = required_date($event->monthly_recurring_week, $event->monthly_recurring_day, $date->format('Y-m-01'));
        if($event->event_date < $event->recurring_end_date) { // check for wrong date or not exist event
        //problem in this code for next months wrong date
           for($event->event_date; $event->event_date < $event->recurring_end_date;){
               $event->event_date = $event->event_date;
               $events[] = (array) $event;
               $date->modify('Next month');
               $event->event_date = required_date($event->monthly_recurring_week, $event->monthly_recurring_day, $date->format('Y-m-01'));
           }
        }
function required_date($week_num, $day, $date) {

    $week_of_year = sprintf('%02d', date('W', strtotime($date)) + $week_num);
    $day_of_week  = date('N', strtotime($day));
    $timestamp    = strtotime(date('Y') . '-W' . $week_of_year . '-' . $day_of_week);
    return  date('Y-m-d H:i:s', $timestamp);
}

这对于当月来说非常有效,但是对于下一个月它会给我加1周的约会! 请帮助!

1 个答案:

答案 0 :(得分:0)

你遗漏了很多问题并没有回答我的评论中的问题,所以我采取了一种天真的方法来回答这个问题,并假设第一周的第一天是本月的第一天,不管它到底是哪一天。

我已经使用了PHP的DateTime类。您应该仔细阅读本手册的这一部分,并学习如何使用这些非常有用的课程。

您需要的输出在问题中不明确,因此我创建的函数返回\DateTime的实例,以便您可以根据需要对其进行格式化。

/** 
 * Returns the date of the given day in a given month.
 * 
 * @param String $month The month in question eg January, September
 * @param Ind $week_num The number of the week, remembering that some months will have a 5th week
 * @param String $day The day to find eg 'Monday'
 * 
 * @return \DateTime
 */
function required_date($month, $week_num, $day)
{
    /**
     * @var \DateTime[] $weeks
     */
    $weeks = array();
    $firstDayOfMonth = new \DateTime("1st $month");
    $lastDayOfMonth = new \DateTime($firstDayOfMonth->format('t M Y'));
    $oneDay = new DateInterval('P1D');
    $period = new \DatePeriod($firstDayOfMonth, $oneDay, $lastDayOfMonth->add($oneDay));

    foreach($period as $date)
    {
        /** @var \DateTime $date */
        $weekNumber = ceil((int)$date->format('d')/7);
        $weeks[$weekNumber][$date->format('l')] = $date;
    }
    return $weeks[$week_num][$day];
}

echo required_date('September', 1, 'Tuesday')->format('Y m d');

<强>输出:

  

2013 09 03