简体   繁体   中英

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();
}

I have done this function where it will return me with an array like date => value so at this function. it is returning the date from the database as YMD so it is what returns to the views too. But how can I change the format of the date to DMY in either the controller or the views?

I like to convert date formats using the PHP DateTime class. Here's an example:

$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');

Best practise is make one helper functions (that will be accessible from any views) like this.

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

and use inside view {{convertDate($date)}}

Or you can write this code inside controller as well.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM