查找php中两个日期之间的天数(以逗号分隔)

时间:2018-05-09 06:23:21

标签: php yii2

我有逗号分隔的日子(1,3,5,6),我想计算两天之间的天数。

我这样做了如下。

String expectedURL = "https://whatever...";
String linkURL = driver.findlement(locator).getAttribute("href");
Assert.assertEquals(expectedURL , linkURL);

此代码工作正常。但问题是两个日期之间的差异是一年还是一年多,而不是循环365次或更多。

有没有办法减少执行时间来计算天数。或者可以使用mysql查询获得天数。

真实情景:我有一个具有开始日期的事件,它在一周内发生多次(即星期一和星期三),我想知道从开始日期到现在的事件发生的次数。如果开始日期是2018-04-9,今天是2018-05-9,则计数将为9

5 个答案:

答案 0 :(得分:2)

这不需要循环。

我发现开始和结束之间有多少周,并且整整几周(在您的示例中为16,17,18)与天数相乘。
然后我发现第一周(15)有多少天高于或等于开始日的天数 然后是第19周的对立面。

$days="1,3"; // comma saperated days
$days=explode(',',$days); // converting days into array


$count=0;
$start_date = "2018-04-09";
$end_date = "2018-05-09";

// calculate number of weeks between start and end date
$yearW = floor(((strtotime($end_date) - strtotime($start_date)) / 86400)/7);

if($yearW >0) $count = ($yearW -1)*count($days); //full weeks multiplied with count of event days    

$startday = date("N", strtotime($start_date));
$endday = date("N", strtotime($end_date));

//find numer of event days in first week (less than or equal to $startday)
$count += count(array_filter($days,function ($value) use($startday) {return ($value >= $startday);}));

//find numer of event days in last week (less than $endday)
$count += count(array_filter($days,function ($value) use($endday) {return ($value < $endday);}));


echo $count; // 9

https://3v4l.org/9kupt

增加$ yearW以保持一周

答案 1 :(得分:1)

在这里,我有一个我之前在项目中使用过的代码。它用于查找从今天起的日期之间的距离。

public function diffFromToday($date){
        $today = date('jS F, Y');

        $today = str_replace(',','',$today);
        $today=date_create($today);
        $today = date_format($today,"Y-m-j"); 

        $date = str_replace(',','',$date);
        $date=date_create($date);
        $date = date_format($date,"Y-m-j");

        $today=date_create($today);
        $date=date_create($date);

        $diff=date_diff($today,$date);
        $result = $diff->format("%R%a");
        $result = str_replace('+','',$result);
        return $result;

    }

您可以根据自己的要求使用此功能。此函数中使用的日期格式为'jS F, Y'请勿混淆并使用您自己的格式进行转换。

答案 2 :(得分:1)

$start_date =  date_create('2018-03-27');
$end_date = date_create('2018-04-27');
$t = ceil(abs($endDate- $start_date) / 86400);
echo date_diff($start_date, $end_date)->format('%a');

像这样输出

396

答案 3 :(得分:0)

您是否可以使用date-&gt; diff函数来获取可以直接使用的值,如-5或5?

$diffInDays = (int)$dDiff->format("%r%a");

Here适用于格式参数说明,如果它对您有帮助的话。

答案 4 :(得分:0)

您可以使用tplaner/when库:

$days = str_replace(
    ['1',  '2',  '3',  '4',  '5',  '6',  '0',  '7'], 
    ['mo', 'tu', 'sa', 'th', 'fr', 'sa', 'su', 'su'],
    '1,3'
);

$when = new When();
$when->rangeLimit = 1000;
$occurrences = $when->startDate(new DateTime('2018-04-9'))
    ->freq('daily')
    ->byday('mo,we')
    ->getOccurrencesBetween(new DateTime('2018-04-9'), new DateTime('2018-05-9'));

echo count($occurrences);
相关问题