I am using Laravel 5.1
Few days ago I used protected $dates = ['license_expire'] in my model to convert the string date to Carbon instances. In HTML the default value in create form for the date was Carbon\Carbon::now()->format('Y-m-d')
In order to show alert in home page i used <p>Licence Expired: <b>{{ $employee->license_expire < Carbon\Carbon::now()?'License has expired':$employee->license_expire->diffForHumans() }}</b></p>
Till then diffForHumans() method works fine.
But in that case the edit form's default value also was today's date no matter what was in database(I am using a partial form). To resolve it I change the default value in HTML was NUll. And add another method in my model to show current date in create form.
public function getLicenseExpireAttribute($date)
{
return Carbon::parse($date)->format('Y-m-d');
}
After that when i go to home page i have an FatalErrorException which says Call to a member function diffForHumans() on string
When I check the date with dd($employee->license_expire) it become STRING again.
Can anybody tell me how can I convert the string to Carbon in this situation?
or
Make my create form's default date as today's date, the edit form's date from database and I can use diffForHumans() to show alert in home page?
You were almost there.
Remove protected $dates = ['license_expire']
and then change your LicenseExpire accessor to:
public function getLicenseExpireAttribute($date)
{
return Carbon::parse($date);
}
This way it will return a Carbon instance no matter what.
So for your form you would just have $employee->license_expire->format('Y-m-d') (or whatever format is required) and diffForHumans() should work on your home page as well.
If you're using Laravel 9+, you can alternatively use the updated syntax for defining Accessors :
use Illuminate\Database\Eloquent\Casts\Attribute;
public function licenseExpire(): Attribute
{
return Attribute::make(
get: fn ($value) => Carbon::parse($value);
);
}
Why not try using the following:
$dateTimeString = $aDateString." ".$aTimeString;
$dueDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $dateTimeString, 'Europe/London');
$filter['dateOfService']='06.2021';
$d1 = Carbon::createFromFormat('m.Y', $filter['dateOfService'], 'Europe/Warsaw')->format('m.Y');
Try this
$date = Carbon::parse(date_format($youttimestring,'d/m/Y H:i:s'));
echo $date;
Related
example i am passing this date in $date = 2020-12-28 15:15:53
and
in db approve_date = 2020-12-28 15:15:00
i am trying to get all the record of date only like this 2020-12-28
so i tried
public function getdatedInvoice($date)
{
$invoices = Invoice::where('user_id' , Auth::id())->where('is_approved' , 1)->whereDate('approve_date' , $date)->get();
dd($invoices);
return view('approved_invoices', compact('invoices'));
}
but when i try to use whereDate it gives me nothing how i can get that data according to date?
First of all, by default, Laravel will only process the approve_date column from your database as a string, even if you set it as a date_time column.
To make Laravel process it as a real date instead, you need to add this to the top of your Invoice model:
class Invoice extends Model {
protected $dates = [
'approve_date'
];
}
Now you will be able to make date comparisons without getting weird errors.
To make your date formatted the way you want, you can go about it in 2 ways.
You can either set a default date formats on every date column in your model by adding this also to the model:
protected $dateFormat = 'Y-m-d';
https://laravel.com/docs/5.2/eloquent-mutators#date-mutators
You can also do this at runtime in your view: {{ \Carbon\Carbon::parse($invoice->approve_date)->format('Y-m-d') }}
'approve_date' is not a variable... you are missing the $ sign. It should be something like this:
$invoices = Invoice::where('user_id' ,
Auth::id())->where('is_approved' , 1)->whereDate('$approve_date' ,
$date)->get();
that variable is not being declared in the function;
After all that, you have your date like date/time and you should convert the format using (for example) Carbon https://carbon.nesbot.com/docs/
I want to get last record updated time in a proper format. Right now updated_at field is default laravel field. The code below return through API as json data: updated_at: "2020-08-01T09:10:01.000000Z"
This is not readable. I tried different conversion method, No one worked.
Code in controller:
public function index()
{
$updatedon = Corona::all('updated_at')->last();
return $updatedon;
}
There are two ways you can do
in your Corona model you can add
public function getUpdatedAtAttribute($date)
{
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d');
}
you can change the format as you wish, you can read more about Accessor
while getting the last record you can do
collect(Corona::all('updated_at')->last())->map(function ($updated_at) {
return Carbon\Carbon::createFromTimeString($updated_at)->format('Y-m-d');
}))
or simply you can do this
$last_record = Corona::all('updated_at')->last();
return \Carbon\Carbon::createFromTimeString($last_record->updated_at)->format('Y-m-d');
By default, Eloquent converts the timestamps columns to instances of Carbon
$updateon->diffForHumans();
https://carbon.nesbot.com/docs/#api-humandiff
This will give you human readable format like 1 day ago, etc
OR
to any custom format
$updateon->format('Y-m-d');
I have my VitalSignSet model:
class VitalSignSet extends Model
{
protected $dates = [
'datetimetaken',
];
. . .
}
Now in my function I have this function which returns the json encoded encounter with the latest vital sign set. (Encounter has a hasMany relationship with VitalSignSet) Before the return though, I would like the datetimetaken field to be formatted for human readability, but just for this particular method. (which is why I did not use accessors)
public function get(Request $request, Encounter $encounter) {
// Setting the latest vital sign set
$encounter->latest_vitals = $encounter->VitalSignSets()
->orderBy('datetimetaken','desc')->get()->first();
// Formatting the date :
// Works when just returning the date.
// Does not return in this format when returning the model with the date.
$encounter->lastest_vitals->datetimetaken->format('M j, Y');
return $encounter->toJson();
}
The above method is accessed from a js ajax request. When I parse and log the response, the datetimetaken format hasn't changed. (still in YYYY-mm-dd H:i:s format) But when I return just $encounter->latest_vitals->datetimetaken; after formatting, a string is returned with the format I set. But when I return the containing VitalSignSet model $encounter->latest_vitals; (json response), the format is in YYYY-mm-dd. Why is that?
This is because you're only accessing the data object, you're not actually changing it.
Unfortunately, there is no way (that I've been able to find) to edit the format of the Carbon instance in the model. This is because Laravel uses the same format to parse the datetime from the database as it does to format it to a string.
Also, you won't be able to just assign the formatted string to the original as Eloquent will try and parse that string (and fail).
One way (if you want/need to keep the key as datetime) would be to convert the output to an array, edit the value, and then return that:
$latestVitals = $encounter->VitalSignSets()
->orderBy('datetimetaken', 'desc')->first();
$encounter->latest_vitals = collect($latestVitals->toArray())
->pipe(function ($item) use ($latestVitals) {
$item['datetimetaken'] = $latestVitals->datetimetaken->format('M j, Y');
return $item;
});
return $encounter;
If you don't mind changing the key to be something else (e.g. formatted_datetimetaken) you could add an accessor to what ever model is used for you VitalSignSet:
public function getFormattedDatetimetakenAttribute()
{
return $this->datetimetaken->format('M j, Y');
}
And then just use append() i.e.
$encounter->latest_vitals = $encounter->VitalSignSets()
->orderBy('datetimetaken','desc')
->first()->append('formatted_datetimetaken');
Finally, you could simply edit the datetime in your js with something like http://momentjs.com/docs. Assuming your response it assigned to the variable response:
response.latest_vitals.datetimetaken = moment(response.latest_vitals.datetimetaken, "YYYY-MM-DD HH:mm:ss")
.format("MMM D, YYYY")
Hope this helps!
I have a datepicker plugin to pop-up a calendar view to allow users to select a date + time, however the format which it produces is:
May 9, 2016 8:30 AM
When storing to the database, I need the format to be:
2016-09-05 08:30:00
In the controller of my application, I have:
public function save(Request $request)
{
Entry::create($request->all());
return redirect('entries');
}
Which saves the users form input, however it doesn't save the datetime due to the incorrect format. I have tried creating a new function to format the date before entering it into the database.
public function formatDate($data)
{
$returnDate = DateTime::createFromFormat('Y-d-m G:i:s', $data);
return $returnDate->format('Y-d-m G:i:s');
}
However when I call the function from the save function, it says undefined function. Am I doing something wrong or what would be the correct way to achieve this?
You have to set the correct format for DateTime::createFromFormat(). Create from format means, you have to tell a pattern to match any information in the given date. For your date, the pattern is:
DateTime::createFromFormat('F j, Y g:i A', $data);
Here is a demo: https://eval.in/567629
A list of all format options: http://php.net/manual/en/function.date.php
Both functions are inside the model?
If so, how are you trying to call the formatDate function?
You could use an anonymous function instead, try:
$formatted_date = function() use ($data) {
$returnDate = DateTime::createFromFormat('Y-d-m G:i:s', $data);
return $returnDate->format('Y-d-m G:i:s');
};
Inside your controller or model.
In Laravel, the created_at and updated_at are casted to Carbon objects
https://laravel.com/docs/5.2/eloquent-mutators#date-mutators
With your date, you could do the same thing
class User extends Model
{
/**
* The attributes that should be mutated to dates.
*
* #var array
*/
protected $dates = ['created_at', 'updated_at', 'your_date'];
}
then, when saving the date, it will be cast to the correct format.
Give that a try and let us know how you get on!
For example;
$data = "May 9, 2016 8:30 AM";
return date('Y-d-m H:i:s',strtotime($data));
Hi i have function where i need to take values from dropdownlist(in 3 dropdownlists i have year, month, day like in facebook registration). I want to set date from this 3 values.
public function setDate()
{
$month=$this->month+1;
$date = date_create();
date_date_set($date, $this->year,$month, $this->day);
return date_format($date, 'Y-m-d');
}
then in my controller i want to save my date but it doesnt work.
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->setDate();
$model->save();
Which method of date can i use to this operation where i can give my values in parameters?
i try this method too
public function setDate()
{
$month=$this->month+1;
$date = new DateTime();
$date ->setDate($this->year,$month, $this->day);
return $date->format('Y-m-d');
}
but i have
Argument 1 passed to Faker\Provider\Base::__construct() must be an instance of Faker\Generator, none given, called in E:\htdocs\mesport\frontend\modules\settings\models\Profile.php on line 119 and defined
In your custom method you actually don't change the model attribute value. Assuming this method is located inside model, replace return line by:
$this->yourDateAttribute = ...;
Also make sure this attribute is safe in current scenario.