Reputation: 33
I'm working on the backend for an App for school and I got a problem converting a date that I get from a request like "Thu Apr 11 2019 00:00:00 GMT+0200" to MySQL format (timestamp).
public function getAll(Request $request){
$start = $request->input('start');
$end = $request->input('end');
// we receive some thing like:
// Thu Apr 11 2019 00:00:00 GMT+0200 (Central European Summer Time)
$sales = Sale::with('SaleLine.lens','SaleLine.cadre','cli_sale')
->whereBetween('created_a', [$start, $end])
->orderBy('id', 'desc')->get();
for ($i=0; $i < count($sales); $i++) {
$sales[$i]['client_name'] = $sales[$i]['cli_sale']['first_name'] . " " . $sales[$i]['cli_sale']['last_name'];
}
return response()->success(['sales'=>$sales]);
}
Upvotes: 3
Views: 2047
Reputation: 9693
You can use Carbon::parse()
and get it like
>>> Carbon\Carbon::parse('Thu Apr 11 2019 00:00:00 GMT+0200')
=> Carbon\Carbon @1554933600 {#3119
date: 2019-04-11 00:00:00.0 +02:00,
}
>>> Carbon\Carbon::parse('Thu Apr 11 2019 00:00:00 GMT+0200')->toDateTimeString(
);
=> "2019-04-11 00:00:00"
Rewriting your code will be
public function getAll(Request $request){
$start = $request->input('start');
$end = $request->input('end');
$start = Carbon\Carbon::parse($start)->toDateTimeString();
$end = Carbon\Carbon::parse($end)->toDateTimeString();
// we receive some thing like:
// Thu Apr 11 2019 00:00:00 GMT+0200 (Central European Summer Time)
$sales = Sale::with('SaleLine.lens','SaleLine.cadre','cli_sale')
->whereBetween('created_at', [$start, $end])
->orderBy('id', 'desc')->get();
for ($i=0; $i < count($sales); $i++) {
$sales[$i]['client_name'] = $sales[$i]['cli_sale']['first_name'] . " " . $sales[$i]['cli_sale']['last_name'];
}
return response()->success(['sales'=>$sales]);
}
Upvotes: 1
Reputation: 16688
On my server this works:
function gmt2mysql($gmt)
{
return date("Y-m-d H:i:s", strtotime($gmt));
}
and
Thu Apr 11 2019 00:00:00 GMT+0200
becomes
2019-04-10 22:00:00
which MySQL can understand. It is the DATETIME type.
Do check carefully if this actually does work for you. Working with time can be tricky.
Clearly it doesn't work on your server, so we have to be a bit more explicit. You could try this altenative:
function gmt2mysql($gmt)
{
$date = DateTime::createFromFormat("D M j Y H:i:s ???O", $gmt);
$date->setTimezone(timezone_open('GMT'));
return $date->format('Y-m-d H:i:s');
}
Here we make the assumption that the timezone offset in your dates will always be GMT. Is it?
Upvotes: 2