从数组php中获取给定日期的天数 [英] get number of days from given dates in a array php
问题描述
我正在尝试从第一个日期到第二个日期的天数,然后从第二个日期到第三个日期等等。
我有一个这样的数组
I am trying to get the number of days from the first date to the second date, and then from the second date to the third date and so on. I have a array like this
$dates = array(
2016 - 02 - 01,
2016 - 03 - 01,
2016 - 04 - 01,
2016 - 05 - 01,
2016 - 06 - 01,
2016 - 07 - 01,
2016 - 09 - 01,
2016 - 11 - 01,
2016 - 12 - 01,
2017 - 01 - 01,
2017 - 12 - 01
);
我想获得从2016-02-01到20163-01的天数,然后从2016-03-01到20164-01等等,如果你注意到日期有一些差距,因为他们跳了超过1个月。
我想要这样一个数组
I want to get the number of days from 2016-02-01 to 2016-03-01, and then from 2016-03-01 to 2016-04-01 and so on, if you notice there are some gaps in the dates as in they do jump for more than 1 month. And I want it in a array like this
array()(
[0] => 0,
[1] => 30,
[2] => 60
//so on ...
)
这是我这样做,但是我收到错误,如 uninitialized string offset
我想我的做法是错误的,最可能的是
Here is how I am doing it but I am getting errors like uninitialized string offset
and I guess the way I am doing is wrong most probably
public function rangeDates()
{
$dates = array(
'2016-02-01',
'2016-03-01',
'2016-04-01',
'2016-05-01',
'2016-06-01',
'2016-07-01',
'2016-09-01',
'2016-11-01',
'2016-12-01',
'2017-01-01',
'2017-12-01'
);
$datez = array();
$index = 0;
$indexone = 1;
foreach($dates as $date)
{
$datez = round(abs(strtotime($date[$index]) - strtotime($date[$indexone])) / 86400);
$index++;
$indexone++;
}
echo $datez;
}
日期为字符串格式,额外信息我忘了提到,这些日子需要加入,例如,如果我们只花了几年的时间。
The dates are in string format, extra information that I forgot to mention is that the days needs to get added, for example if we take just the years
array(11) (
[0] => (int) 0
[1] => (int) 365
[2] => (int) 730
[3] => (int) 1095
[4] => (int) 1460
[5] => (int) 1825
[6] => (int) 2190
[7] => (int) 2555
[8] => (int) 2920
[9] => (int) 3285
[10] => (int) 3650
推荐答案
,循环通过日期数组,然后相应地计算日期的差异。您的循环将运行一个总数组大小的一个,从间隔中调用几天,并将其存储在数组中。
This is all about you need, Loop through the dates array then calculate the difference of the dates accordingly. Your loop will be run one short of the total array size, From the interval just call for the days and store it in an array.
$dates = array(
"2016-02-01",
"2016-03-01",
"2016-04-01",
"2016-05-01",
"2016-06-01",
"2016-07-01",
"2016-09-01",
"2016-11-01",
"2016-12-01",
"2017-01-01",
"2017-12-01"
);
$datez = array();
$date = array();
$datez[] = 0;
for($i = 1; $i < count($dates) - 1; $i++){
$start_date = $dates[$i-1];
$end_Date = $dates[$i];
$date1 = new DateTime($start_date);
$date2 = new DateTime($end_Date);
$interval = $date1->diff($date2);
$date[] = $interval->days;
$datez[] = array_sum($date);
}
print_r($date);
print_r($datez);
这篇关于从数组php中获取给定日期的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!