簡體   English   中英

如何在使用Carbon傳遞到視圖之前更改日期格式

[英]how to change date format before passing to views using carbon

public function graphheheByDate(Request $request, $companyID)
{
  $companyID = $this->decode($companyID);

  $matchs = DiraChatLog::whereBetween('date_access', [$request->from, $request->to])->orderBy('date_access', 'asc')->get();
  foreach ($matchs as $key => $match) {
    $time = strtotime($match->date_access); 
    $newformat = date('Y-m-d',$time);
    $a[$newformat] = $this->testing($newformat,$match);
  }

  dd($a);

  $user = array_values($a);
  $dates = array_keys($a);
  // dd($user, $dates);

  $from = $request->from;
  $to = $request->to;
  // dd($from, $to);

  $companyID = $this->encodeID($companyID);

  return view('AltHr.Chatbot.graphhehe', compact('companyID','from','to', 'dates'))->with('user',json_encode($user,JSON_NUMERIC_CHECK))->with('dates',json_encode($dates,JSON_NUMERIC_CHECK));     
}


private function testing($date,$match)
{
  $a = Carbon::parse($date)->addDay()->toDateTimeString();
  // dd($a,$date);

  $noOfUsers = DiraChatLog::whereBetween('date_access', [$date,$a])->get();
  // dd($noOfUsers);

  return $noOfUsers->groupBy('user_id')->count();
}

我已經完成了此功能,它將以類似date => value的數組返回我,因此在此功能中。 它以YMD從數據庫中返回日期,所以它也返回視圖。 但是,如何在控制器或視圖中將日期格式更改為DMY

我喜歡使用PHP DateTime類轉換日期格式。 這是一個例子:

$oFrom = DateTime::createFromFormat('Y-m-d', $from);
$oTo = DateTime::createFromFormat('Y-m-d', $to);

// Change the format
$from = $oFrom->format('d/m/Y');
$to = $oTo->format('d/m/y');

您應該嘗試以下解決方案

Carbon::parse($date)->addDay()->format('d-m-Y');

最佳實踐是像這樣使一個輔助函數(可從任何視圖訪問)。

function convertDate($date) {
    return date('d-m-y', startotime($date));
}

並使用內部視圖{{convertDate($ date)}}

或者,您也可以在控制器內部編寫此代碼。

 $from = date('d-m-y', strtotime($request->from));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM