Reputation: 2000
consider that i have 2 dates like below in my view :
{{$property->start_date }} //which is for example 3/20/219
and another date
{{$property->end_date }} //which is for example 3/28/219
now i want to some how print these 8 days of difference as 8 col-lg-1 some how like below code
@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
how can i achieve that in blade considering this that i am doing this in my view and is it reasonable at all to do it in view or not .
Upvotes: 1
Views: 4135
Reputation: 4987
You can use the CarbonPeriod
from Carbon
something like this
$ranges = CarbonPeriod::create('2019-03-01', '2019-03-31');
To print each date you can use the loop
foreach ($ranges as $date) {
echo $date->format('Y-m-d');
}
Or you can convert it to array as well
$dates = $ranges->toArray();
Upvotes: 6
Reputation: 1379
You can try this on template directly (only if there no way or if it's difficult to pass it from controller to view)
@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>
but if you do it in controller and send it to template it would be better
Upvotes: 1
Reputation: 1981
Return all dates between two dates in php:
Using DatePeriod
and DateTime
:
$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>';
}
Output:
2019-03-21
2019-03-22
2019-03-23
2019-03-24
2019-03-25
2019-03-26
2019-03-27
Using 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>';
Output:
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
)
I hope it would helpful.
Upvotes: 2
Reputation: 129
If you want to get date diff , you can use Carbon
and diffInDays
.
$date1 = Carbon::parse($property->start_date);
$date2 = Carbon::parse($property->end_date );
$diff = $date1->diffInDays($date2);
dd($diff);
Upvotes: 1