如何使用PHP查找两天 not dates 之间的天数?
我知道如何获取两个日期之间的天数,但我的输入值是日期名称(日期无知)。
输入/输出:
Wednesday
和Saturday
返回3
Sunday
和Wednesday
返回3
答案 0 :(得分:3)
使用PHP date_diff()
函数(docs)。
$datetime1 = date_create($date_1);
$datetime2 = date_create($date_2);
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%d'); // For days
根据澄清,您可以创建任意的星期六和星期三来计算它:
$datetime1 = date_create(date('Y-m-d',strtotime('wednesday')));
$datetime2 = date_create(date('Y-m-d',strtotime('saturday')));
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%d'); // For days
会返回“3”,但取决于你运行它。
答案 1 :(得分:1)
您的任务似乎根本不需要日期功能。一个简单的查找数组就足够了。
代码:(Demo)
function daysUntil($start,$end){
$lookup=['Sunday'=>0,'Monday'=>1,'Tuesday'=>2,'Wednesday'=>3,'Thursday'=>4,'Friday'=>5,'Saturday'=>6];
$days=$lookup[$end]-$lookup[$start];
return "From $start to $end: ".($days<1?$days+7:$days);
}
echo daysUntil('Wednesday','Saturday'),"\n"; // Thursday, Friday, Saturday
echo daysUntil('Monday','Friday'),"\n"; // Tuesday, Wednesday, Thursday, Friday
echo daysUntil('Thursday','Thursday'),"\n"; // [assumed next week]
echo daysUntil('Friday','Monday'),"\n"; // Saturday, Sunday, Monday
echo daysUntil('Saturday','Sunday'),"\n"; // Sunday
echo daysUntil('Sunday','Saturday'),"\n"; // Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
echo daysUntil('Sunday','Wednesday'); // Monday, Tuesday, Wednesday
输出:
From Wednesday to Saturday: 3
From Monday to Friday: 4
From Thursday to Thursday: 7
From Friday to Monday: 3
From Saturday to Sunday: 1
From Sunday to Saturday: 6
From Sunday to Wednesday: 3
或者您可以使用4个函数调用替换查找数组:
$days=date('w',strtotime($end))-date('w',strtotime($start));
http://sandbox.onlinephpfunctions.com/code/b349aae527654d25a3dbd92df2a3dde386ca423a
答案 2 :(得分:0)
您可以在新的DateTime类中编写要解析的日期名称:
<?php
$datetime1 = new DateTime('Sunday');
$datetime2 = new DateTime('Wednesday');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>
也低于一行版本:
echo (new DateTime('Sunday'))->diff(new DateTime('Wednesday'))->format('%a days');
答案 3 :(得分:0)
public function numOfDaysBetween($start,$end)
{
$days=[0=>'Saturday',1=>'Sunday',2=>'Monday',3=>'Tuesday',4=>'Wednesday',5=>'Thursday',6=>'Friday'];
$index_start=array_search($start, $days);
$index_end=array_search($end, $days);
if($index_start==$index_end)
{
return 7;
}else if($index_start<$index_end)
{
return $index_end-$index_start;
}else
{
return 7-($index_start-$index_end);
}
}