如何在laravel中接收2个日期之间的所有天数

cgh8pdjw  于 2022-11-18  发布在  其他
关注(0)|答案(4)|浏览(116)

考虑到我有2个日期像下面在我看来:

{{$property->start_date }} //which is for example 3/20/219

和另一个日期

{{$property->end_date }} //which is for example 3/28/219

现在我想一些如何打印这8天的差异作为8 col-lg-1一些如何像下面的代码

@while($property->start_date  <= $property->end_date)

//here i want to print dates in col-lg-1 i dont know how to access the day and if the while loop is working right or no

我怎么能实现这一点,在刀片考虑到这一点,我这样做,在我看来,这是合理的,在所有这样做的看法或没有。

xwmevbvl

xwmevbvl1#

您可以使用Carbon中的CarbonPeriod
像这样的东西

$ranges = CarbonPeriod::create('2019-03-01', '2019-03-31');

要打印每个日期,可以使用循环

foreach ($ranges as $date) {
    echo $date->format('Y-m-d');
}

也可以将其转换为数组

$dates = $ranges->toArray();
afdcj2ne

afdcj2ne2#

返回php中两个日期之间的所有日期:
使用DatePeriodDateTime

$begin = new DateTime($property->start_date); // your start date 2019-03-20
$begin = $begin->modify( '+1 day' );
$end = new DateTime($property->end_date); // your end date 2019-03-28

$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);

foreach ($daterange as $date) {
    echo '<pre>'.$date->format('Y-m-d').'<pre>'; 
}

输出:

2019-03-21
2019-03-22
2019-03-23
2019-03-24
2019-03-25
2019-03-26
2019-03-27

使用strtotime

// Declare two dates 
$Date1 = $property->start_date; // 2019-03-20
$Date2 = $property->end_date; // 2019-03-28

// Declare an empty array 
$array = array(); 

// Use strtotime function 
$start = strtotime($Date1. '+1 day'); 
$end = strtotime($Date2. '-1 day'); 

// Use for loop to store dates into array 
// 86400 sec = 24 hrs = 60*60*24 = 1 day 
for ($currentDate = $start; $currentDate <= $end; $currentDate += (86400)) { 

    $Store = date('Y-m-d', $currentDate); 
    $array[] = $Store; 
} 

// Display the dates in array format
echo '<pre>';
print_r($array);
echo '<pre>';

输出:

Array
(
    [0] => 2019-03-21
    [1] => 2019-03-22
    [2] => 2019-03-23
    [3] => 2019-03-24
    [4] => 2019-03-25
    [5] => 2019-03-26
    [6] => 2019-03-27
)

我希望这对你有帮助。

5jdjgkvh

5jdjgkvh3#

如果你想得到日期差异,你可以使用CarbondiffInDays

$date1 = Carbon::parse($property->start_date);
$date2 = Carbon::parse($property->end_date );

$diff = $date1->diffInDays($date2);
dd($diff);
n3ipq98p

n3ipq98p4#

您可以直接在模板上尝试此操作(仅当无法或难以将其从控制器传递到视图时)

@php
    $date1 = \Carbon\Carbon::parse('2019-01-31 10:15:23');
    $date2 = \Carbon\Carbon::parse('2019-02-15 10:15:23');
    $diff = $date1->diffInDays($date2);
@endphp

<div>{{$diff}}</div>

但如果在控制器中执行并将其发送到模板,

相关问题