Laravel Carbon failed to parse time string error - php

I import datas from excel with excel maatwebsite laravel to a mysql db, I dunno why but I see that in Excel date column are in text format (and only if i click ENTER inside each cell it became date format),
so the only method to import automatically them that i found is
public function model(array $row)
{
$year_pd = Carbon::parse($row[7])->format("Y");
$day_pd = Carbon::parse($row[7])->format("m");
$month_pd = Carbon::parse($row[7])->format("d");
$hour_pd = Carbon::parse($row[7])->format("H");
$minute_pd = Carbon::parse($row[7])->format("i");
$pickup_date = Carbon::create($year_pd, $month_pd, $day_pd, $hour_pd, $minute_pd);
$year_dd = Carbon::parse($row[8])->format("Y");
$day_dd = Carbon::parse($row[8])->format("m");
$month_dd = Carbon::parse($row[8])->format("d");
$hour_dd = Carbon::parse($row[8])->format("H");
$minute_dd = Carbon::parse($row[8])->format("i");
$drop_date = Carbon::create($year_dd, $month_dd, $day_dd, $hour_dd, $minute_dd);
return new Driveme([
'targa' => $row[14],
'modello' => $row[13],
'driver' => $row[10],
'pickup_date' => $pickup_date,
'drop_date' => $drop_date,
//'pickup_date' => Carbon::createFromFormat($row[7]),
//'drop_date' => Carbon::createFromFormat($row[8]),
]);
but at certain point importation stops and it gives me this error
Could not parse '13/06/2021 19:00':
DateTime::__construct(): Failed to parse time string (13/06/2021 19:00) at position 0 (1): Unexpected character
All dates have the same format, so why it stops casually on a date if they are all similar?
If I use Carbon::createFromFormat($row[7]) it tell me that format date is incorrect
Thx

As I mentioned, 13/06/2021 is being parsed as m/d/Y, due to the PHP strtotime rules. Other dates may appear work because the first digit is between 1-12, but you won't be getting the actual date that you want (You send 01/06/2021 expecting June 1st, but Carbon will return January 6th)). You need to pass the format into the createFromFormat function:
Carbon::createFromFormat('d/m/Y H:i', $row[7]);

Related

Laravel format time column in blade

In Laravel I know I can use Carbon to format dates into more readable strings. Is there a way to do this for a time column like {{ $event->time->format('h i') }}? All I see in all my searches are related to datetime columns. A lot of the apps I do are for schedules so there is a "Start" time and "End" time. For these I use $table->time('starts'); in my migrations, not a timestamp. The trouble is when I use the field in Blade, I need to format it in 12 hr AM/PM format and I can never find a good way.
try
in the model make sure you have the field in the cast array
protected $casts = [
'created_at' => 'datetime:h i',
];
$event->time->format('h i')->toTimeString()
try below also
public function getformattedAttribute()
{
return \Carbon\Carbon::createFromFormat('h i', $this->attributes['time']);
}
and run it with $event->formatted
Depending on your implementation, you might have some unreliable time generated on conversion, basically because of timezone so I will post with the assumption that you're using something like below:
$table->timeTz('start'); or $table->time('start');
The Difference there is the timezone which can produce incorrect value on conversion as mentioned above.
So, for you to generate format such as 12hr AM/PM which in reality should look like 12:00 PM or 12:00pm or 12:30 PM .....
We can do something like below:
public function dateTest(){
$sampleTimeFromDb = "12:00:00"; //This is the basic sample time you're expected to get from your db ...
$sampleTimeFromDbFormated = Carbon::createFromTimeString($sampleTimeFromDb)->format('g:i a'); // am/pm, you can change a to A to get AM/PM
//Other samples which basically will generate same sample but with time stamp specified
$sampleCurrentTimeLag = Carbon::createFromTimeString("12:00:00","Africa/Lagos");
$sampleCurrentTimeReg = Carbon::createFromTimeString("01:00:00","America/Regina");
$def_format_ = Carbon::createFromTimeString($sampleCurrentTimeLag)->format('g:i A'); //Without timezone AM/PM
$lagosFormat = Carbon::createFromTimeString($sampleCurrentTimeLag, "Africa/Lagos")->format('g:i a');; //with timezone am/pm
$def_format_0 = Carbon::createFromTimeString($sampleCurrentTimeReg)->format('g:i A'); //Without timezone AM/PM
$americaFormat = Carbon::createFromTimeString($sampleCurrentTimeReg, "America/Regina")->format('g:i a');; //with timezone am/pm
$data = [
'_' => $sampleTimeFromDbFormated,
'a' => $def_format_,
'b' => $lagosFormat,
'c' => $def_format_0,
'd' => $americaFormat,
'e' => $americaFormat
];
return View("playground", $data);
}
My view playground.blade.php
<!DOCTYPE html>
<html>
<body>
<p>{{$_}}</p>
<p>{{$a}}</p>
<p>{{$b}}</p>
<p>{{$c}}</p>
<p>{{$d}}</p>
<p>{{$e}}</p>
</body>
</html>
Output:
Hopefully it does help.

Getting only time from Carbon object

Im reading an excel file a column with values like "1:45:00. But when print_r($value["time"]) this value from my array I got a Carbon object like this:
Carbon\Carbon Object
(
[date] => 2018-10-30 01:45:00.000000
[timezone_type] => 3
[timezone] => America/US
)
Then, when I insert to a bulk array my value with:
"time"=>$value["time"]
In the database I got: 2018-10-30 01:45:00
How can I insert only 01:45:00 and not the entire timestamp?
EDIT: I thought that $value["time"]->date->format("H:i:s") would works but I got the error "Trying to get property 'date' of non-object"
EDIT 2: This is how I read the data:
The excel is like:
date time
---------- -------
30-10-2018 01:45:00
The code where I read the excel:
$data = Excel::selectSheetsByIndex(0)->load($path, function($reader) {
})->get()->toArray();
foreach ($data as $key => $value) {
$time = Carbon::createFromFormat('Y-m-d h:i:s',$value["time"])->format('h:i:s');
print_r($time);
die();
}
The output:
Call to a member function format() on null
What you need is the formatting here:
$dt = Carbon::now();
$dt->toTimeString(); //14:15:16
Carbon\Carbon is an extension to php's DateTime, so you can read at php.net to learn more.
Although America/US is not a valid timezone, so there's something going on with that.
Anyway,
In the database I got: 2018-10-30 01:45:00
If your data type is a TIMESTAMP or a DATETIME, mysql will always have a date component for data in that column.
First, let's get the time out of the $value array to make the rest of the discussion easier to understand and debug:
$time = $value["time"];
From here on out, pay no attention to the internal fields revealed by var_dump. They may or may not actually exist like that in the object. Use the mostly-well-documented interface methods documented in the link above or in the Carbon docs. The fields given by var_dump will just confuse you otherwise.
If you just want the time of day represented as a string, you use the DateTime::format() method:
$timestr = $time->format('H:i:s');
Note that if you insert that string in a database with a DATETIME column type, it won't work. Mysql will require a string that includes date information.
The code snippet that follows doesn't seem to match with the code you show above:
$data = Excel::selectSheetsByIndex(0)->load($path, function($reader) {
})->get()->toArray();
foreach ($data as $key => $value) {
$time = Carbon::createFromFormat('Y-m-d h:i:s',$value["time"])->format('h:i:s');
print_r($time);
}
You are trying to create a Carbon instance using the createFromFormat() method. The first parameter you provide tells Carbon (actually DateTime) what the format of your input string will be. The data you are supplying is H:i:s (assuming $value["time"] is read from the time column of your Excel sheet), but you're telling Carbon that you will be giving it Y-m-d h:i:s. Since the format you promise doesn't match the data you are giving the object, null is resulting.
Either (broken into to steps for clarity):
$time = Carbon::createFromFormat('H:i:s', $value["time"]);
$timestr = $time->format('h:i:s');
or
$time = Carbon::createFromFormat('d-m-Y H:i:s', $value["date"] . " " . $value["time"]);
$timestr = $time->format('h:i:s');
will work.
The second one gives you a Carbon object that is much more useful - the first one will probably default to year zero. In both cases the timezone will be the zone of the machine the code is running on. You can override that if necessary.
Note that if I'm confused and the Excel reader is actually returning Cabon objects rather than strings, you can eliminate the whole createFromFormat code altogether. No sense making a Carbon object out of a Carbon object.

Unable to set column of type Date using Parse.com PHP SDK - invalid type

I'm pretty new to Parse.com. I've been using the PHP SDK to try and populate some data. I've had no issues so far other than not being able to set date values against objects that have a column of type "Date".
My code:
$uploadDate = date("Y-m-d\TH:i:s.u",$instaPost->created_time);
echo $uploadDate;
$photo->set('uploadDate',$uploadDate);
$photo->save();
The echo call returns: 2015-10-06T19:33:36.000000
Parse gives me an error of:
Failed to create new object, with error message: invalid type for key uploadDate, expected date, but got string
I have also tried:
$uploadDate = array(
"__type" => "Date",
"iso" => date("c", time())
);
and various other combinations and date formats (the first parameter of the date() function).
Does anyone know the correct way of doing this??
Php date() function returns string. So $uploadDate is of type string. But when you try to set it for column type date it is giving error. This should solve your problem.
$date = array(
"__type" => "Date",
"iso" => date("c", $instaPost->created_time)
);
$photo->set('uploadDate',$date);
$photo->save();
I was having the same problem. You are doing it correctly, but you are missing one thing.
Instead of using:
$photo->set('uploadDate',$uploadDate);
try this:
$photo->setArray('uploadDate',$uploadDate);
I'm also using this function that I found on the parse.com forum:
function getProperDateFormat($value)
{
$dateFormatString = 'Y-m-d\TH:i:s.u';
$date = date_format($value, $dateFormatString);
$date = substr($date, 0, -3) . 'Z';
return $date;
}
where $value is a php Date object.
So this is how I put all together:
$date = new DateTime($year."-".$month."-".$day);
$puzzle->setArray( "date", ["__type" => "Date", "iso" => getProperDateFormat($date)] );
It works perfectly for me

Converting a carbon date to mysql timestamp.

I have a timestamp variable column in a mysql database. Trying to convert a carbon timestamp to something that I can input there, but Carbon::now() only returns a Carbon object and when I try to use the timestamp string of the Carbon object, it does not register in mysql.
public function store(CreateArticleRequest $request){
$input = $request->all();
var_dump($input); // JUST SO YOU CAN SEE
$input['published_at'] = Carbon::now();
var_dump($input); // JUST SO YOU CAN SEE
Article::create($input);
}
My first var dump is like so:
array (size=4)
'_token' => string 'Wy67a4hWxrnfiGz61wmXfYCSjAdldv26wOJiLWNc' (length=40)
'title' => string 'ASDFasdf' (length=8)
'body' => string 'asdfasdf' (length=8)
'published_at' => string '2015-08-26' (length=10)
My second var dump is like so.
The mysql column relating to "published_at" is a timestamp variable. How an I suppose to convert this from a Carbon Object?
Thanks in advance.
The short answer is that toDateTimeString() is what you're looking for:
$input['published_at'] = Carbon::now()->toDateTimeString();
See http://carbon.nesbot.com/docs/ for more options, including toDateString() if you just want the date part and not the time.
But an even better way to handle it would be to let Laravel handle casting the date value to/from a Carbon object for you. See https://laravel.com/docs/5.4/eloquent-mutators#date-mutators.
The problem is in your date string, for example, you have this:
public function setCrbDateAttribute($value)
{
$this->attributes['crb_date'] = \Carbon\Carbon::createFromFormat('d-m-Y h:i', $value);
}
Now, if there is a date like 10-12-2014 then this error will occur because the hour and minute is missing. So you make sure that the date contains all the pars and also make sure that the date string contains - as a separator not /.
In other words, check the $value before you use Carbon and make sure your date string contains exactly the same formatted string you've used in the method.
This also happens in an accessor method, so check the date value first before you use it in Carbon::createFromFormat().
If you are getting the date from user input then validate the date before using it using date or date_format:format rule, check the validation here.
Answer ref:
Laravel/Carbon Timestamp 0000-00-00 00:00:00 or Unexpected data found. Unexpected data found. Data missing
You can also set Mutator on your model.
public function setPublishedAt($value)
{
$this->attributes['published_at'] = strtotime($value);
}
to convert to timestamp
$model -> setPublishedAt('2015-08-26'); // 1440572400
or you can just convert the date to timestamp using strtotime
strtotime — Parse about any English textual datetime description into a Unix timestamp
Hope this help.

How to query mongodb Date using php

I need to convert this query from php to mongoDB query
$query = "select * from table where data_added like '%data%';
I have date stored in variable
$date = "2013-09-02";
and in my mongo Document the date sorted as :
$dateAdded = new MongoDate(strtotime('2013-09-02 12:21:55'));
I tried
$date = new MongoDate(strtotime("$date"));
$mongo->find(array('date_added'=>array('$lt'=>$date)));
and
$mongo->find(array('date_added'=>$date));
but without success .
so I need to query usin (Y-m-d) not (Y-m-d h:i:s)
so how to use LIKE query for data in mongo
Thanks
You need to do a range query. Create a timestamp, for example using strtotime(), to get the unix timestamp at the start of the day, and another one and the end of the day.
Depending on if you want these two ends inclusive or exclusive, you then use
// Both points/seconds inclusive
->find(array("date" => array('$gte' => $startOfDay, '$lte' => $endOfDay)));
// Both seconds exclusive
->find(array("date" => array('$gt' => $startOfDay, '$lt' => $endOfDay)));
See http://cookbook.mongodb.org/patterns/date_range/

Categories