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);
Related
I have to output this information but I am not used to work with PHP, donĀ“t know what I am doing wrong.
I query woocommerce order date like this:
$order = wc_get_order(456);
$orderdate = $order->date_created;
That seems to be working ok, it returns a date in this format:
2020-10-15T17:38:37-03:00
For current date, I create a variable like this:
$date = date('d-m-y h:i:s');
But when I try to output the difference in days between order date and current, it always give me 0
This is how I tried to calculate the difference:
function dateDiff($date1, $date2)
{
$date1_ts = strtotime($date);
$date2_ts = strtotime($orderdate);
$diff = $date2_ts - $date1_ts;
return round($diff / 86400);
}
$dateDiff = dateDiff($date1, $date2);
echo ("day difference is: " . $dateDiff );
Thanks a lot for reading, hope you can help me.
Short explanation of what is wrong with your code:
$dateDiff = dateDiff($date1, $date2);
In your case dateDiff is a function which expects two parameters $date1 and $date2. But you are passing non existing variables to the function. They do not exist out of the function scope, because you didn't declare them.
Then you are trying to get timestamps from dates which are in parent scope and probably getting NULL as a result from both cases :)
$date1_ts = strtotime($date);
$date2_ts = strtotime($orderdate);
Small improvements:
Its better to use DateTime class when you are working with dates. DateTime class has powerful method called format that allows you to output date in suitable format for you.
If we combine what you did into one piece of code with some changes, then we will get this:
$order = wc_get_order(456);
$order_date = new DateTime($order->date_created);
$current_date = new DateTime();
function dateDiff($date1, $date2)
{
// check if diff is not equal to zero in order to avoid division be zero exception
if ($diff = abs(strtotime($date2) - strtotime($date1))) {
return round($diff / 86400);
}
return 0;
}
echo ("day difference is: " . dateDiff(
$current_date->format('d-m-Y h:i:s'),
$order_date->format('d-m-Y h:i:s')
) . " days");
Hi I am trying to get an array of leave dates from my Leave table. I want to be able to get the dates from the start_date to end_date column of each row of leave data I have in 'Y-m-d' format in order to compare with my getDays method whichis in 'Y-m-d' format.
Below is the method I currently have in my controller class:
private function getLeaves()
{
$leavesList = Leave::where('clinic_id', '=', $_SESSION['clinic_ID'])->get();
$leavesArray = json_decode($leavesList, true);
foreach($leavesArray as $leave){
//Convert each data from table to Y-m-d format to compare
$leaves[] = CarbonPeriod::create(date('Y-m-d', strtotime($leave['start_date'])), date('Y-m-d', strtotime($leave['end_date'])));
}
return $leaves;
}
Currently the output is this:
[["2021-05-20T16:00:00.000000Z"],["2021-05-06T16:00:00.000000Z","2021-05-07T16:00:00.000000Z"]]
Your problem is that the function CarbonPeriod::create() returns a period object. If you want to get each day in this period, you need to iterate in this period and format your date.
public function getLeaves()
{
$leavesList = Leave::where('clinic_id', '=', $_SESSION['clinic_ID'])->get();
$leavesArray = json_decode($leavesList, true);
foreach($leavesArray as $leave){
//Convert each data from table to Y-m-d format to compare
$days = CarbonPeriod::create(
date('Y-m-d', strtotime($leave['start_date'])),
date('Y-m-d', strtotime($leave['end_date'])));
foreach ($days as $day) {
$leaves[] = $day->format('Y-m-d');
}
}
return $leaves;
}
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);
I need to compare two dates and find which date is greater.
$actual_date = Carbon::createFromFormat('d-m-Y',$night_out->actual_return_date);
$expected_date = Carbon::createFromFormat('d-m-Y', $night_out->expected_return_date);
$days = $expected_date->diffInDays($actual_date); // gives the days count only
Thanks in Advance!
You can use carbon method greaterThan()
if($actual_date->greaterThan($expected_date)){
// logic here
}
Carbon is an extension of datetime and inherits all properties of the base class. DateTime objects and thus carbon objects are directly comparable. Special comparison methods are not needed for this case.
if($actual_date > $expected_date){
// do something
}
If only the date which is greater is needed, you can do that
$max_date = max($actual_date , $expected_date);
Note: $ max_date is an object reference of $actual_date or $expected_date. You can get a copy with the copy () method or use clone.
$max_date = max($actual_date , $expected_date)->copy();
Use gt function for that:
$actual_date = Carbon::createFromFormat('d-m-Y',$night_out->actual_return_date);
$expected_date = Carbon::createFromFormat('d-m-Y', $night_out->expected_return_date);
if($expected_date->gt($actual_date)){
return $expected_date; //Max date
} else {
return $actual_date; //Min date
}
OR:
You need to find a greater date from two dates using max and array_map function like:
$actual_date = Carbon::createFromFormat('d-m-Y',$night_out->actual_return_date);
$expected_date = Carbon::createFromFormat('d-m-Y', $night_out->expected_return_date);
// store dates value into an array to find the max date.
$date = array();
$date['actual_date'] = $actual_date;
$date['expected_date'] = $expected_date;
$max = max(array_map('strtotime', $date));
echo date('d-m-Y', $max);
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.