我目前正在为我个人使用的日历脚本。所以我需要你的帮助:-)数组与日期在两个不同的日期
我有两个日期的格式YYYY-MM-DD。
例如:
2012-05-12 and
2012-05-16
我需要的是日期,两者之间:
2012-05-13
2012-05-14
2012-05-15
输出应该在数组中。反正我现在不怎么开始......所以你有提示吗?
我目前正在为我个人使用的日历脚本。所以我需要你的帮助:-)数组与日期在两个不同的日期
我有两个日期的格式YYYY-MM-DD。
例如:
2012-05-12 and
2012-05-16
我需要的是日期,两者之间:
2012-05-13
2012-05-14
2012-05-15
输出应该在数组中。反正我现在不怎么开始......所以你有提示吗?
function getDates($startTime, $endTime) {
$day = 86400;
$format = 'Y-m-d';
$startTime = strtotime($startTime);
$endTime = strtotime($endTime);
//$numDays = round(($endTime - $startTime)/$day) + 1;
$numDays = round(($endTime - $startTime)/$day); // remove increment
$days = array();
for ($i = 1; $i < $numDays; $i++) { //change $i to 1
$days[] = date($format, ($startTime + ($i * $day)));
}
return $days;
}
$days = getDates('2012-05-12', '2012-05-16');
输出:
Array
(
[0] => 2012-05-13
[1] => 2012-05-14
[2] => 2012-05-15
)
正如丹·李说,我改变了功能,仅保留日期间隔,不包括阵列的第一天和最后一天。
只是你的函数名称是不一样的:D – user1137370 2012-07-12 12:27:30
是的,谢谢你的编辑建议。 – Ovidiu 2012-07-12 12:40:44
你没有得到这个功能所需的结果。 – 2012-07-12 15:35:22
$date = date("Y-m-d", strtotime("2012-05-12"));
$final_date = date("Y-m-d", strtotime("2012-05-16"));
while($date < $final_date){
$date = date("Y-m-d", strtotime($date . " +1 day"));
$dates[] = $date;
}
这也是我的做法。不要忘记掉在代码框外面的最后一个大括号! :) – SilverSnake 2012-07-12 12:17:18
function GetDays ($sStartDate, $sEndDate) {
$sStartDate = gmdate('Y-m-d', strtotime($sStartDate));
$sEndDate = gmdate('Y-m-d', strtotime($sEndDate));
$aDays[] = $sStartDate;
$sCurrentDate = $sStartDate;
while($sCurrentDate < $sEndDate) {
$sCurrentDate = gmdate('Y-m-d', strtotime('+1 day', strtotime($sCurrentDate)));
$aDays[] = $sCurrentDate;
}
return $aDays;
}
print_r ('2012-05-12', '2012-05-16');
这里的OOP方法,你应该使用它:
$a = new DateTime('2012-05-12');
$b = new DateTime('2012-05-16');
// to exclude the end date (so you just get dates between start and end date):
// $b->modify('-1 day');
$period = new DatePeriod($a, new DateInterval('P1D'), $b, DatePeriod::EXCLUDE_START_DATE);
foreach($period as $dt) {
echo $dt->format('Y-m-d');
}
进一步的阅读可见DateTime,DateInterval和DatePeriod。
下面是代码:
function createDateRangeArray($strDateFrom,$strDateTo)
{
// takes two dates formatted as YYYY-MM-DD and creates an
// inclusive array of the dates between the from and to dates.
// could test validity of dates here but I'm already doing
// that in the main script
$aryRange=array();
$iDateFrom=mktime(1,0,0,substr($strDateFrom,5,2), substr($strDateFrom,8,2),substr($strDateFrom,0,4));
$iDateTo=mktime(1,0,0,substr($strDateTo,5,2), substr($strDateTo,8,2),substr($strDateTo,0,4));
if ($iDateTo>=$iDateFrom)
{
array_push($aryRange,date('Y-m-d',$iDateFrom)); // first entry
while ($iDateFrom<$iDateTo)
{
$iDateFrom+=86400; // add 24 hours
array_push($aryRange,date('Y-m-d',$iDateFrom));
}
}
return $aryRange;
}
我从this网站采取了参考。
http://stackoverflow.com/faq – 2012-07-12 12:13:24
[将缺失的日期添加到数组]可能的重复(http://stackoverflow.com/questions/4187323/add-missing-dates-to-an-array) – JJJ 2012-07-12 12:36:07