A textual month could not be found ,Trailing data Carbon - laravel - laravel

I did try different ways, but I have not get the proper time format.
$news->created_at = Carbon::parse($news->created_at)->format('M, d, Y');
$news->created_at = date('d M Y',strtotime($news->created_at))
$news->created_at = date('d M Y',$news->created_at)
$news->created_at = Carbon::createFromFormat("d M Y",strtotime($news->created_at));
$news->created_at = $news->created_at->format('M, d, Y');
And the errors are,
Unexpected data found
The separation symbol could not be found
InvalidArgumentException
Carbon.php: 910
dd($news->created_at);
Carbon #1550035143 {#361 ▼
date: 2019-02-13 05:19:03.0 UTC (+00:00)
}

You already have a Carbon instance in your $news->created_at field, because Eloquent models consider the created_at and updated_at columns as timestamps by default and automatically convert them to Carbon instances. So you just need to use the format method from Carbon:
$news->created_at->format('d M Y');
However, when you try to reassign a string as the value of created_at on the model instance, it conflicts with Laravel's internal mutator that tries to convert any value assigned to a date field from a Carbon instance into a string.
You could set public $timestamps = false; in your News model and then use strings throughout your app when handling model timestamps, but that seems like a hack more than a solution, because you'd be giving up on all the benefits that Carbon offers.
You also could also do this by handling timestamps at serialization time, something like this:
return collect($news->makeHidden(['created_at']))->merge([
'created_at' => $news->created_at->format('d M Y')
]);
The above code will hide the columns passed to makeHidden from the serialization process. Then you could merge the formatted values for the hidden columns into your response.

Related

Laravel eloquent compare datetime with query builder

I'd like to compare datetime values (with date AND time). First I tried this, but it does not work, as it only compares the date, not the time:
$events = $events->whereDate('end', '>=', $input['after']);
I thought that a simple where would help, but it does not:
$events = $events->where('end', '>=', $input['after']);
The reason for that is, that my input value is 2022-10-10T00:00:00 and the database read gives 2022-10-10 00:00:00 (the T in the middle was added in the input).
I'd like to stick to the isoformat (using the T), however inside the database that format gets casted to a value without T it seems. The reason for that might be the cast in the model: 'end' => 'datetime',
What would be the best way to solve this issue and compare datetime objects (and how)?
Change the model cast
Cast the input
What would be the best way to solve this issue and compare datetime objects
The best way is still to convert the input with the data type format of the date and time column
You can use : $dateConvert = date('Y-m-d H:i:s', strtotime($input['after']));
But I suggest you use carbon library :
$dateConvert = \Carbon\Carbon::parse($input['after'])->format('Y-m-d H:i:s');
And :
$events = $events->where('end', '>=', $dateConvert );

Laravel - different formats for date/time query

I am learning Laravel and I have some small problem on controllers - when I use DB, the query returns date time without timezone but if I use model, the query returns full datetime.
public function test($switch)
{
//return "YYYY-MM-DDThh:mm:ss.000000Z"
if ($switch) return Position::select('id','created_at')->orderBy('id')->get();
// return "YYYY-MM-DD hh:mm:ss"
return DB::table('positions')->select('id','created_at')->orderBy('id')->get();
}
Why? What I need to dof I want "YYYY-MM-DDThh:mm:ss.000000Z" on both cases?
Thanks for solution.
thanks for advice
You should use the DB::raw
The following statement will convert the datetime value created_at from +00:00 timezone to +10:00 timezone.
You can try this
return DB::table('positions')->select(DB::raw('id',CONVERT_TZ('created_at','+00:00','+10:00'))->orderBy('id')->get();
you can set your timezone that you wants to convert it
They are the same data, probably just different classes of date and you can always format your date. Laravel utilizes Carbon date library which is excellent and should be used primarily.
If you try to print out your date class with get_class() for Eloquent Position created_at, you probably got Carbon and DB::table('positions') created_at, you probably got DateTime and that's why the value looks different (but you still got the same date).
If you want to convert your DateTime to Carbon, you can do
$newDate = new \Carbon\Carbon($position->created_at)
Thanks Anurat,
I realized this fact shortly after sending the previous question.
... but there is another 'issue' - both times are my local time - time in "YYYY-MM-DDThh:mm:ss.000000Z" is not UTC time as I expected.
I changed my function:
public function test($switch = false)
{
$data = Position::selectRaw('id, created_at, UNIX_TIMESTAMP(created_at) unix')->orderBy('id')->get();
foreach ($data as $d) {
$conv = new \DateTime($d->created_at);
$d->conv = intval($conv->format('U'));
$d->diff = $d->conv - $d->unix;
}
return $data;
}
... and result is
0
id 1
created_at "2021-03-18T12:36:59.000000Z"
unix 1616067419
conv 1616071019
diff 3600
As you see, the difference is 1 hour (as my timezone offset). Where is a problem?
Thanks.

Converting String Values into Date using Carbon Laravel

The sql field type is VARCHAR, I am saving date and time from an API. The format that I get is 2018-04-28T22:17:41+05:30. Now I need to convert this using carbon to get a format like 04 April 2018 and timings. I couldn't convert varchar filed value into date format which I needed.
And the expected format should be passed to view, I did that using ( $ticket->dateOfIssue and it's giving this - 018-04-28T22:17:41+05:30 ). But as I said, I need the expected format (which is 04 April 2018, time ).
You should either use Accessor on your model or set the datetime format on your model. The example of the former is:
use Carbon/Carbon; before your class declaration
public function getDateOfIssueAttribute($value) {
return Carbon::parse($value)->format('d M Y , H:m:s');
}
When ever you retrieve this model anywhere you already have it in the format you set in your accessor.
Here is an example to parse the date
Carbon::parse('2018-04-28T22:17:41+05:30')->format('dd MM YYYY');
Moreover, do not forget to import the Carbon namespaces on the top
You try
use use Carbon\Carbon; // on top
$time = Carbon::parse('2018-04-28T22:17:41+05:30')->format('d M Y'); //28 Apr 2018
Good luck
This is the exact format for date and time. First of all include carbon library in your controller
use Carbon\Carbon;
class abc extend Controller
{
public function cancell()
{
$ticket = Booking::all()->where('status', '=', 'CANCELLED');
$dateOfIssue=$ticket->dateOfIssue;
$time = Carbon::parse($dateOfIssue)->format('d M Y , H:m:s');
return view('Admin.Tickets.cancelledTickets')->with('ticket', $ticket);
}
}
If you have multiple records then you can use loop for that
Please try ,
\Carbon\Carbon::parse('2018-04-28T22:17:41+05:30')->format('d- M- Y');
the output is 28- Apr- 2018
using sql
DATE_FORMAT(mydate, '%d-%M-%Y')

How to get unique year values from created_at?

I have a collection called $products, each instance of which has a field created_at. The latter obviously has a format ('Y-m-d H:i:s') in the DB. Now, it's easy to get instances with unique created_at. However, I'd like to retrieve unique year values of created_at in one single expression (that I can write in my view). What I am looking for is:
$products->unique( year value ('Y' ONLY) of 'created_at' )
This expression should evaluate to something like this: ['2012', '2013', '2016'].
Building on the comment that gives you a collection with unique timestamps, you can map out the year and sort with the following code.
$years = $products->unique(function($item){
return $item['created_at']->year;
})->map(function($item){
return $item['created_at']->year;
})->sort()->toArray();
In addition to Tim result
$products = DB::table('products')->get();
$years = $products->unique(function($item){
return $item['created_at']->year;
})->map(function($item){
return $item['created_at']->year;
})->sort()->toArray();
You can use toArray or values() to get the result of collection

How to use whereBetween for dates in Laravel

I am trying to get the number of new users for each week using the created_at column. I am trying to use the whereBetweensyntax but it always return 0 even when it is suppose to return otherwise.
{{ DB::table('users')
->whereBetween('created_at', array(date("Y/m/d h:i:s", strtotime('sunday last week')), date("Y/m/d h:i:s", strtotime('saturday this week'))))->count(); }}
Any suggestions?
The query itself should work as written, though you might want to verify that created_at is a column of either timestamp, date, or datetime type. When you created the users table, did you use a migration to create your users table, and if so, did you specify $table->timestamps();? Or did you manually define the created_at column, and perhaps set it to a string?
A couple other (unrelated) suggestions:
• It appears that you're running this query in a view, echoing the count using blade. This logic would be better handled elsewhere, perhaps in your User model, and the result passed to the view by the controller.
• You can simplify your query using PHPs DateTime object, replacing your date(...strtotime...) with date_create(...):
$usersThisWeek = User::whereBetween(
'created_at', array(
date_create('sunday last week'),
date_create('saturday this week')
))->count();

Resources