Converting String Values into Date using Carbon Laravel - 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')

Related

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.

A textual month could not be found ,Trailing data Carbon - 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.

Laravel Nova: Convert Datetime to readable output

Is there an option in Laravel Nova to display an readable date-time output and/or limit the output?
For example to : 29. October 2018 / 11. November 2018, 12:10 am
Code:
DateTime::make('Start')
->rules('required')
->sortable(),
As per documentation https://nova.laravel.com/docs/1.0/resources/fields.html#datetime-field
use Laravel\Nova\Fields\DateTime;
DateTime::make('Start')->format('DD MMMM YYYY'),
Must use Moment.js formatting rules https://momentjs.com/docs/#/displaying/format/
This is achieved in Nova 4.0+ with the displayUsing method:
DateTime::make('Updated', 'updated_at')
->displayUsing(fn ($value) => $value ? $value->format('D d/m/Y, g:ia') : '')
use this, hope it will works
Date::make('start')->format('F j, Y'),
We also faced such a problem.
This solution DateTime::make('Start')->format('DD MMMM YYYY'), helps only for index page, but didn't help for Edit page.
I don't know when this bug will be fixed in new Nova releases but we temporary used small hardcoding.
nova/src/Fields/Date.php
instead: return $value->format('Y-m-d');
use this one: return $value->format('m/d/Y');
nova/resources/js/components/Form/DateField.vue
In this vue component also should be changed a date format: dateFormat="m/d/Y".
nova/resources/js/components/Form/DateField.vue
For placeholder method use this one:
return this.field.placeholder || moment().format('MM/DD/YYYY')
Instead this:
return this.field.placeholder || moment().format('YYYY-MM-DD')
Also You should use Mutator in Your App\Model class if you store data in the database in another format. Something like this:
public function setLastUsedAttribute($value){
$date = Carbon::createFromFormat('m/d/Y', $value);
$this->attributes['last_used'] = $date->format('Y-m-d');
}

Laravel: Check if time + 4 hours has passed

I store in my database a date format like this:
2017-02-22 16:55:40
I added it to my database like this:
Carbon::now();
I need to check if 4 hours passed since this date.
How I can do this? I couldn't figure out how I can convert this format into Carbon or timestamp.
If you are using Laravel and the date is a Carbon instance from a Model you have access to the whole Carbon API.
You can use the Difference API of Carbon for this specific purpose.
echo $model->thedate->diffInHours($now, false);
If your model does not threat the date as a carbon instance you can cast it by adding the date to the dates array of the current model like so
protected $dates = [
'field_name',
];
Check out Date casting for more information
Update with an explicit example
$user = User::first();
// This will return the difference in hours
$user->created_at->diffInHours(Carbon\Carbon::now(), false);
You can convert it to a Carbon object with:
Carbon::parse('2017-02-22 16:55:40');

Carbon - A textual month could not be found Trailing data

I'm using Laravel. I get the following error when trying to display a date:
A textual month could not be found Trailing data
Format is j M Y, date is 2014-12-13 10:00:00
I don't get where is the error.
Any toughts?
For future reference: Using createFromFormat with the second parameter not being a Carbon object was giving me this same error. Using Carbon::parse:: instead of createFromFormat seemed to fix the issue:
public function setPublishedAtAttribute($date) {
$this->attributes['published_at'] = Carbon::parse($date);
}

Resources