我想通过给出日期来获取一周中的日期列表。就像如果给出“2013 年 6 月 11 日”,我想将列表作为 PHP 数组,任何帮助将不胜感激
问问题
3293 次
3 回答
3
我建议您在提问之前快速进行谷歌搜索,甚至在 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
)
于 2013-06-11T08:25:32.037 回答
1
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)
这具有处理夏令时更改等的额外优势。
于 2013-06-11T08:57:13.327 回答
-1
您想获取与给定日期对应的日期的全名吗?如果是这样,您可以执行以下操作:
<?php
echo date('l', strtotime('2013/11/06'));
?>
于 2013-06-11T08:24:50.360 回答