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

时间:2019-03-27 06:39:56

标签: php laravel

在我看来,我有两个约会如下:

{{$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

考虑到我在我看来正在这样做,我该如何在刀片中实现这一目标,无论有没有考虑,这样做是合理的。

4 个答案:

答案 0 :(得分:1)

返回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
)

我希望这会有所帮助。

答案 1 :(得分:1)

如果要获取日期差异,可以使用CarbondiffInDays

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

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

答案 2 :(得分:1)

您可以使用Plain Text Before Encryption: AES Symmetric Encryption Decryption Encrypted Text After Encryption: 7UMh49c5Wqb2BzlttKBEnq5g4fxMK9oJs1EUDIgWzVwlY28k+qd/oFG9SJckBsaX6DHp Decrypted Text After Decryption: AES Symmetric Encryption Decryption 中的CarbonPeriod

喜欢这样的人

Carbon

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

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

或者您也可以将其转换为数组

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

答案 3 :(得分:1)

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

@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>

但是如果您在控制器中执行并将其发送到模板,那就更好了