我想从存储在数据库中的Ymd格式计算年龄。如何传递dob的结果(即年龄)。如何以这种格式传递存储的Date(如20岁)。
我的观点:
<th style="width: 10px;text-align: left">Age</th>
@if(count($members)>0)
@foreach($members as $key=>$member)
<tr>
<td>{{$key+1}}</td>
<td>{{$member['dob']}}</td>
@endforeach
@endif
我的控制器:
public function index()
{
$departments = [];
$members = Member::where('status', 0)
->leftjoin('member_details', 'members.cnic', '=', 'member_details.cnic')
->leftjoin('districts','districts.dis_id','=','members.district')
->paginate(100,['members.*','member_details.*','members.id as id','member_details.id as memberid','district','dis_name']);
for ($m = 0; $m <count($members); $m++) {
$finalDep = [];
$getDepartments = MemberInterestDepartment::where('cnic' , $members[$m]['cnic'])
->leftjoin('departments','departments.dep_id','=','member_interest_departments.department')
->get(['department','dep_name'])->toArray();
if(count($getDepartments)>1){
for($r=0; $r<count($getDepartments); $r++){
$finalDep[] = $getDepartments[$r]['dep_name'];
}
}else{
$finalDep = $getDepartments[0]['dep_name'];
}
$departments[] = array(
'id' => $members[$m]['id'],
'cnic' => $members[$m]['cnic'],
'name' => $members[$m]['name'],
'district' => $members[$m]['dis_name'],
'party_joining_year' => $members[$m]['party_joining_year'],
'dob' => $members[$m]['dob'],
'qualification' => $members[$m]['qualification'],
'profession' => $members[$m]['profession'],
'department' => $finalDep,
);
}
$allDepartments = Department::all();
return view('dashboard')->with(['pages' => $members,'members' => $departments, 'province' => $province, 'division' => $division, 'districts' => $districts, 'departments' => $allDepartments]);
}
答案 0 :(得分:1)
首先导入控制器
use Carbon\Carbon;
然后在解析中传递dob值
$dob = '1990/01/15';
echo Carbon::parse($dob)->age .' years';
这是您的操作方式:
$departments[] = array(
'id' => $members[$m]['id'],
'cnic' => $members[$m]['cnic'],
'name' => $members[$m]['name'],
'district' => $members[$m]['dis_name'],
'party_joining_year' => $members[$m]['party_joining_year'],
'dob' => Carbon::parse($members[$m]['dob'])->age .' years',
'qualification' => $members[$m]['qualification'],
'profession' => $members[$m]['profession'],
'department' => $finalDep,
);
答案 1 :(得分:0)
我不确定这一点,但我希望它会有所帮助 Laravel使用碳包来封装日期https://carbon.nesbot.com/
Carbon内置了功能toDateString()
,它将转换时间戳,例如
例如,假设这是通过使用函数
1998-03-10 07:37:45
toDateString ('1998-03-10 07:37:45')
结果将在Y-m-d format as(1998-03-10)
之后
并将微小功能添加到相应的模型中
public static function carbonDatesToAge($toDateFormat)
{
$dateOfBirth = "$toDateFormat";
$dateOfBirthToYear = new \DateTime($dateOfBirth);
$todaysDate = new \DateTime();
echo $todaysDate->diff($dateOfBirthToYear)->y;
}
最后是您的视图文件
方法一
<td>{{ App\Models\PersonalDetail::carbonDatesToAge($item->date_of_birth->toDateString()) }}</td>
仅在方法一失败时使用
<td>{{ App\Models\PersonalDetail::carbonDatesToAge(Carbon\Carbon::parse($item->date_of_birth)->format('Y-m-d')) }}</td>
只需将模型名称更改为Member
并在视图中使用它即可
如果发现任何困难,请在下面评论
享受!!!!