Convert Datetime to PHP
-
02-01-2020 - |
Question
I have a datetime string as such 14/04/2014 4:57:16 PM
and I am using carbon datetime to work on it.
However as soon as I try to do this
$dt = Carbon::createFromTimestampUTC($encDateTime);
However I am getting parse errors : DateTime::__construct(): Failed to parse time string (@14/04/2014 5:03:45 PM ) at position 3 (/): Unexpected character.
Udpate : I tried doing this :
$date = DateTime::createFromFormat('d/m/Y H:i A', $encDateTime);
dd($date->format('Y-m-d H:i:s'));
and I get the following error Call to a member function format() on a non-object
Can you please help me out with this?
Thanks
Solution
Your date string contains a space at the end - that's why DateTime::createFromFormat()
fails to parse it. To remove the extra whitespace from the beginning and/or end, you could use trim()
.
Also, you were originally using H
, which is the 24-hour format with leading zeroes. In this case, it looks like you have a 12-hour format, so use g
instead (h
would work, too).
The following should work:
$date = DateTime::createFromFormat('d/m/Y g:i:s A', trim($encDateTime));
When you receive such errors, always var_dump()
the values. That way, you can check if the variable contains what you think it does.
OTHER TIPS
The static method createFromFormat
from DateTime returns NULL
when there is a parse error. The format that was given (d/m/Y H:i A
) was wrong. Hence the error "Call to a member function format()
on a non-object".
You can create DateTime objects from non-standard timestrings like this:
$time = '14/04/2014 4:57:16 PM';
$date = Carbon\Carbon::createFromFormat('d/m/Y g:i:s A', $time);
The different format characters available and their explanations can be found in the documentation for date()
.
I don't know anything about Carbon, but this works. You were using a two digit (H) instead of h (edit: g is the same exact thing) in your createFromFormat method:
$encDateTime = "14/04/2014 4:57:16 PM";
$date1 = DateTime::createFromFormat('d/m/Y h:i:s A', trim($encDateTime));
echo $date1->format('Y-m-d H:i:s');
result:
2014-04-14 16:57:16
just use laravel date function as:
$productsales=DB::table('tbl_trans')
->leftjoin('tbl_product','tbl_product.prod_id','=','tbl_trans.product_id')
->select(DB::raw('count(product_id) as quant'),'product_id','tbl_product.name','tbl_product.code','tbl_product.price')
->groupBy('product_id','code','name','price')
->whereDate('tbl_trans.created_at','2017-07-29')
->get();
return view('reports.productsales',compact('productsales'));