Reputation: 241
I have a leave system where user select dates from
and to
dates let say 2018-02-26
- 2018-03-03
that is 6 days in total. On our portal it shows all users that is on leave. supposing that this user applied for 6 days leave, How am I going to display this user for 6 days on our portal?below is my code it works well but is show only for the current date.
$currentDate = date('Y-m-d');
$lf = Leave::where('leave_from', $currentDate)
->where('status', 'approved')
->get();
I am using eloquent. thanks
Upvotes: 1
Views: 625
Reputation: 1
$many_days=0;
$date_from = "2018-02-26";
$date_to = "2018-03-03";
for ($i=strtotime($date_from); $i<=strtotime($date_to);
$i+=86400) {
$many_days++;
}
echo "leaves $many_days";
Upvotes: 0
Reputation: 6565
You can use DateTime function of PHP in your case
$currentDate = date('Y-m-d');
$currentDate = new DateTime($currentDate);
$leaveDate = new DateTime($leaveFrom);
$difference = $currentDate->diff($leaveDate);
You will get result like
DateInterval Object ( [y] => 0 [m] => 0 [d] => 5 [h] => 0 [i] => 0 [s] => 0 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 0 [days] => 5 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )
Upvotes: 1
Reputation: 34924
You can use DATEDIFF
to get difference directly from query.
Select abs(DATEDIFF(`date_to`,`date_from`)) as diff from leaves;
In laravel you can write it as
$lf = Leave::where('status', 'approved')
->select(DB::raw("abs(DATEDIFF(`date_to`,`date_from`)) as diff"),"*")
->get();
Be sure to use where('leave_from', $currentDate)
, I think it's not necessary.
Upvotes: 1
Reputation: 3540
You can use datetime function in PHP.
$first_date = new DateTime($currentDate);
$last_date = new DateTime($if);
$difference = $first_date->diff($last_date);
echo $difference->d.' days;
if you want month and year use $difference->m
and $difference->y
.And if you want accurate days even dates are negative use below one.
$result = $first_date->diff($last_date)->format("%r%a");
source:/ datetime
Upvotes: 2
Reputation: 268
// Specify the start date. This date can be any English textual format
$date_from = "2018-02-03";
$date_from = strtotime($date_from); // Convert date to a UNIX timestamp
// Specify the end date. This date can be any English textual format
$date_to = "2018-02-10";
$date_to = strtotime($date_to); // Convert date to a UNIX timestamp
// Loop from the start date to end date and output all dates inbetween
for ($i=$date_from; $i<=$date_to; $i+=86400) {
echo date("Y-m-d", $i).'<br />';
}
Upvotes: 3
Reputation: 1391
You can use date_diff() function:
$interval = date_diff($currentDate, $lf);
echo $interval->format('%d');
more on: http://php.net/manual/en/function.date-diff.php; https://www.w3schools.com/php/func_date_date_diff.asp
Upvotes: 1