Eloquent & Carbon Time Difference - php

I have a basic table which captures time and attendance.
I'm trying to out put the total hours on site, from my eloquent query:
$attendance = DB::table('staff_attendances')
->whereBetween('in_date', array($date1, $date2))->where('staff_id', $ID)->select('first_name', 'last_name', 'in_date', 'out_date', 'in_time', 'out_time')->get();
I get the following back in json.
[{"first_name":"TestFirst","last_name":"TestLast","in_date":"2016-01-30","out_date":"2016-01-30","in_time":"11:40:34","out_time":"12:41:10"},
{"first_name":"TestFirst","last_name":"TestLast","in_date":"2016-01-30","out_date":"2016-01-30","in_time":"13:02:27","out_time":"14:02:32"}]
Which method would be best to out put total hours on site?
I've tried using carbon with the following:
$startTime = Carbon::parse($attendance->in_time);
$finishTime = Carbon::parse($attendance->out_time);
$totalDuration = $finishTime->diffInHours($startTime);
But I get "Trying to get property of non-object"

Carbon is a class which extends DateTime class. It should deal with date and/or time. But it looks like your parse call don't return a Carbon instance. So I advise you to use a full date format ("Y-m-d H:i:s") as in the following example :
<?php
$totalDuration = 0;
foreach($attendance as $aAttendance){
$startTime = Carbon::parse($aAttendance->in_date.' '.$aAttendance->in_time);
$finishTime = Carbon::parse($aAttendance->out_date.' '.$aAttendance->out_time);
$totalDuration += intval($finishTime->diffInHours($startTime));
}
?>
With the foreach instruction you will go through all the attendances and do the sum of all diffInHours returns in the variable $totalDuration.

Related

PHP date_create_from_format using with object giving bool(false) error

I am trying to use the PHP date_create_from_format on an object so I can use the diff() function to calculate the number of days from when the record was created to today (whenever that is looked at)
If I echo $job->created_date I get something like 2021-2-27 10:05:00
I started with:
$created = $job->created_date;
$date_now = date('Y-m-d');
$job_posted_date_difference = $date_now->diff($created); <<< the error shows on this line
echo $job_posted_date_difference.$difference->d.' days';
but I get a fatal error Call to a member function diff() on string
So....... I thought that it could be a formatting of the initial date issue and then I tried
$created = date_create_from_format('Y-m-d', $job->created_date);
$date_now = date('Y-m-d');
var_dump ($created);
But the dump shows - bool(false)
How do I fix this properly? I looked at a number of other SO issues and they seemed to really range from the dates being in the wrong order( I tried both ways) to the formatting issue .
and if you want to calculate days from two dates
then you can use
$ceated_date = "2021-2-27 10:05:00";
//create a date object of created date and get timestamp.
$t1 = (new DateTime($created_date))->getTimetamp();
//create a date object of now and get timestamp.
$t2 = (new DateTime("now"))->getTimestamp();
//this will give you days
$day_diff = floor(($t2 - $t1) / 86400);

How to compare created_at timestamp with Carbon date In laravel?

I have orders table , I want to get orders that have been created at this month only (delivery process happens at the same day).
I want to compare between the carbon date which refers to this current month with the created_at field of type timestamps for orders.
This is my attempt:
$month = Carbon::today();
$currentMont = $month->month;
$thisMonthOrders = Order::where('place_id',$id)->where('stage',9)->whereDate('created_at',$currentMont)->get();
dd($thisMonthOrders);
The output that it gives me is an empty array.
You'll need to use the MONTH function in MySQL, along with a whereRaw:
$thisMonthOrders = Order::where('place_id',$id)
->where('stage',9)
->whereRaw('MONTH(created_at) = ?',[$currentMont])
->get();
However, you'll have issues when you have multiple years, unless you also add in a YEAR check. You might have better luck with whereBetween instead.
$start = Carbon::now()->startOfMonth();
$end = $start->copy()->endOfMonth();
$thisMonthOrders = Order::where('place_id',$id)
->where('stage',9)
->whereBetween('created_at',[$start, $end])
->get();

Age Calculation error in laravel 5+?

Controller
static function show()
{
//
$output = '';
$result = DB::table('PersonalDetail')
->get();
foreach ($result as $key ) {
$dob = Carbon::$key->DOB;
// We need to compare the user's date of birth with today's date.
$now =Carbon::now();
// Calculate the time difference between the two dates.
$difference = $now->diff($dob);
// Get the difference in years, as we are looking for the user's age.
$age = $difference->y;
$output .= '<p>Age:-'.$age.' </p>';
}
return ($output);
}
View Blade
Call to a member function diff() on string (View: /Applications/XAMPP/xamppfiles/htdocs/WedLaravel/WedLara/resources/views/pages/ViewPeo.blade.php)
I Got this error , I have try lot
To calculate differences in dates using Carbon, you must cast both dates as Carbon objects, and then use the methods provided:
$now = Carbon::now();
$dob = Carbon::createFromFormat('Y-m-d', $key->dob);
$diff = $now->diff($dob);
You'll then have a DateInterval object that will give you the different intervals, so you can use $d->y. Since it's Carbon, there are other methods you can use, such as
$now->diffInDays($dob);
$now->diffForHumans($dob);

how to filter results inside where clause in laravel?

I am new to laravel, I am building a small application which alerts when event date is a week away from current date. Here is my controller code
public function index()
{
$domain_count = domain_details::get()->count();
$domain_alert = domain_details::
where('domain_ex_date','>',date('Y-m-d'))
->get();
}
The domain_ex_date is in the format (YYYY-mm-dd) stored with the help of Carbon. The line where('domain_ex_date','>',date('Y-m-d')) gets me whole record when the domain_ex_date is away from the current date. i.e 2017-06-12 > 2016-09-15 gets the whole record. Here what i want to do is , i want to filter and get the only records which is only a week away from the current date. How do i do this ? i have tried like subweek() and subdays() but nothing helped.
I should get the record only when it satisfies this condition domain_ex_date - current date = 7
You can use strtotime():
domain_details:: where('domain_ex_date','<',date('Y-m-d',strtotime("+7 days")))
-> where('domain_ex_date','>',date('Y-m-d'))
->get();
Use Carbon!
Carbon is a build in date-extension ... Try it! :)
$week = Carbon::now()->addWeek();
$now = Carbon::now();
domain_details::where("domain_ex_date","<" $week)
->where("domain_ex_date", ">" $now)
->get()
Or you could also use the addDays($days) method!
$week = Carbon::now()->addDays(7);
I used carbon and this is what worked well for me
$week = Carbon::now()->subWeek();
$now = Carbon::now();
$domain_count = domain_details::get()->count();
$domain_alert = domain_details::where("domain_ex_date",">", $week)
->where("domain_ex_date", "<" ,$now)
->get();

whereBetween eloquent query returns empty output

I'm trying to use 'whereBetween' eloqouent query with two given start and end dates.
$first_day_this_month = date('Y-m-01 H:s:i'); //get the first day of the current month
$yesterDay = date('Y-m-d H:s:i',strtotime("-1 days")); //get yesterday's date
$d = m_chat_history::where('employee_id',$request->other_id)
->whereNull('to_group')->where('to_employee_id',$request->id)
->whereBetween('created_at',[$yesterDay,$first_day_this_month])
->get();
I make sure I have all the required data for the query by 'var_dump' and it did gives me all the required data needed for the query but the query returns me an empty output. Any ideas, clues, suggestions, help, recommendations please? I tried to remove the 'whereBetween' and my query works like it returns me the expected output but with 'whereBetween', the return output is empty.
Make sure to use the same type and format as created_at when defining the values for whereBetween. As you're using datetime you could define edge values like (just one of many ways of doing it):
$first_day_this_month = date('Y-m-01 H:i:s');
$yesterday = date('Y-m-d H:i:s', strtotime("-1 day"));
Also make sure of the order of params (still please consider edge cases like first day of the month where $yesterday would be smaller, so you have to add some logic and be careful):
->whereBetween('created_at', [$first_day_this_month, $yesterday])
Edit: wasn't timestamp...
Try this,
but first you have to install Carbon with composer.
after doing that
use Carbon
then write the fallowing code
$yesterday = Carbon::yesterday()->toDateTimeString();
$carbon = new Carbon('first day of ' . date('F Y'));
$first_day = $carbon->toDateTimeString();
and in your query
->whereBetween('created_at', [$first_day, $yesterday])

Categories