PHP通过提供日期获取日期列表

时间:2013-06-11 08:20:47

标签: php date datetime

我希望通过提供日期获得一周中的日期列表。喜欢如果给了“06/11/2013”​​我想把列表作为PHP数组,任何帮助将不胜感激

3 个答案:

答案 0 :(得分:2)

我建议您在提问之前快速进行谷歌搜索甚至搜索StackOverflow。正如HamZa在评论中所说 - SO已经涵盖了几乎所有关于日期的内容。

您可以使用以下方式获得答案:

function week_from_monday($date) {
    // Assuming $date is in format DD-MM-YYYY
    list($day, $month, $year) = explode("-", $date);

    // Get the weekday of the given date
    $wkday = date('l',mktime('0','0','0', $month, $day, $year));

    switch($wkday) {
        case 'Monday': $numDaysToMon = 0; break;
        case 'Tuesday': $numDaysToMon = 1; break;
        case 'Wednesday': $numDaysToMon = 2; break;
        case 'Thursday': $numDaysToMon = 3; break;
        case 'Friday': $numDaysToMon = 4; break;
        case 'Saturday': $numDaysToMon = 5; break;
        case 'Sunday': $numDaysToMon = 6; break;   
    }

    // Timestamp of the monday for that week
    $monday = mktime('0','0','0', $month, $day-$numDaysToMon, $year);

    $seconds_in_a_day = 86400;

    // Get date for 7 days from Monday (inclusive)
    for($i=0; $i<7; $i++)
    {
        $dates[$i] = date('Y-m-d',$monday+($seconds_in_a_day*$i));
    }

    return $dates;
}

week_from_monday('07 -10-2008')的输出给出:

Array
(
    [0] => 2008-10-06
    [1] => 2008-10-07
    [2] => 2008-10-08
    [3] => 2008-10-09
    [4] => 2008-10-10
    [5] => 2008-10-11
    [6] => 2008-10-12
)

取自:Calculating days of week given a week number

答案 1 :(得分:0)

DateTime类使这更容易: -

/**
 * Returns an array of date strings for the
 * week of the given date, starting on Monday
 *
 * @param String $date The date in question
 * @return array An array of date strings
 */
function daysInWeek($date)
{
    $result = array();
    $datetime = DateTime::createFromFormat('m/d/Y', $date);
    $interval = new DateInterval('P1D');
    if($datetime->format('D') !== 'Mon')$datetime->modify('last monday');
    $week = new DatePeriod($datetime, $interval, 6);
    foreach($week as $day){
        $result[] = $day->format('m/d/y');
    }
    return $result;
}

var_dump(daysInWeek("06/11/2013"));

返回: -

array (size=7)
  0 => string '06/10/13' (length=8)
  1 => string '06/11/13' (length=8)
  2 => string '06/12/13' (length=8)
  3 => string '06/13/13' (length=8)
  4 => string '06/14/13' (length=8)
  5 => string '06/15/13' (length=8)
  6 => string '06/16/13' (length=8)

这具有额外的优势,可以处理夏令时变化等。

答案 2 :(得分:-1)

您想获取与给定日期对应的当天的全名吗? 如果是这样,你可以这样做:

<?php
    echo date('l', strtotime('2013/11/06'));
?>