获取开始和结束日期之间的所有日期到一个数组 [英] Get all dates between a start and end date into an array

查看:498
本文介绍了获取开始和结束日期之间的所有日期到一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能插入结果到一个数组。

这是我的code:

  $ listData2 =;$结束= DATE(N / D / Y的strtotime($行['dDate']));
$开始=日期(N / D / Y的strtotime($行['ADATE']));$ DATEDIFF =的strtotime($完) - 的strtotime($开始);
$ DATEDIFF =地板($ DATEDIFF /(60 * 60 * 24));为($ I = 0; $ I< = - $ DATEDIFF + 1; $ I ++){
    $ dateArr =日期(N / D / Y的strtotime($开始'+'$ I'日')。);
    $ listData2 [] = $ dateArr;
}


解决方案

您有一个令人费解的方式,这样做,所以我打算只告诉你如何得到所有两个日期之间的日期到一个数组:

  $ listData2 = [];
$开始=新的日期时间($行['dDate']);
$结束=(新的DateTime($行['ADATE'])) - >修改('+1天');
$间隔= DateInterval :: createFromDateString(1一天);
$周期=新DatePeriod($开始,$区间,$结束);的foreach($期间$ DT){
    $ listData2 [] = $ DT-GT&;格式(N / D / Y);
}

<大骨节病>演示

这个初始化一个空数组存储日期(你开始一个空字符串,不是数组)和创建的起始日期和结束日期的日期时间对象(而不是您创建非标准的字符串。然后,它会创建一个的 DateInterval 对象重新presenting 1天,一个的 DatePeriod 反对包裹性都为我们通过DatePeriod对象,然后我们循环工作,并将其添加到阵列中。

(你也有一个无效的操作符(&LT; = - )您的for循环)。

I cant insert the result into an array.

This is my code:

$listData2="";

$end = date("n/d/Y",strtotime($row['dDate']));
$start = date("n/d/Y",strtotime($row['aDate']));

$datediff = strtotime($end) - strtotime($start);
$datediff = floor($datediff/(60*60*24));

for($i = 0; $i <=- $datediff + 1; $i++) {
    $dateArr=date("n/d/Y", strtotime($start . ' + ' . $i . 'day'));
    $listData2[]=$dateArr;
}

解决方案

You have a convoluted way to doing this so I am going to just show you how to get all of the dates between two dates into an array:

$listData2 = [];
$start     = new DateTime($row['dDate']);
$end       = (new DateTime($row['aDate']))->modify('+1 day');
$interval  = DateInterval::createFromDateString('1 day');
$period    = new DatePeriod($start, $interval, $end);

foreach ($period as $dt) {
    $listData2[] =  $dt->format("n/d/Y");
}

Demo

This initializes an empty array to store the dates (you started with an empty string, not an array) and the creates the starting date and end date as DateTime objects (instead of non-standard strings that you created. It then creates a DateInterval object representing 1 day and a DatePeriod object to wrap ity all up for us to work with. Then we loop through the DatePeriod object and add them to the array.

(You also had an invalid operator (<=-) in your for loop).

这篇关于获取开始和结束日期之间的所有日期到一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆