laravel 5 format datetime - php

I have an array that return the following date time:
$item['created_at'] => "2015-10-28 19:18:44"
And I need this outuput:
"2016-08-10T13:15:00.000+10:00"
Exist any function to convert this date?

Try this:
$dt = new \DateTime('2015-10-28 19:18:44', new \DateTimeZone('Europe/London'));
dd($dt->format('c')); // string '2015-10-28T19:18:44+00:00' (length=25)
Alternatively take a look at Carbon

You can use Laravel's accessors to get "reformatted" created_at.
public function getCreatedAtAttribute($value)
{
//Since Laravel uses Carbon you can do.
return $value->format('c');
}
This way anytime you do something like $model->created_at it will return modified created_at.
If you want to change datetime format for created_at in your database as well, you can use mutators.
More information you can find on the Laravel's docs page.

Related

how to get specific date result in laravel?

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/

How Can I convert Laravel default timestamp of created_at filed in a Controller and return through API

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');

Different date accessors in same Model

I have this, and it works nicely to give me UK-formatted dates:
protected $dateFormat = 'd-m-Y';
protected $dates = ['purchased', 'warranty_expires', 'scrapped_on', 'location_date', 'user_date'];
However, I also have created and modified (not the standard Laravel ones, but my own) that are Timestamps, not dates. How can I automate the formatting of those two fields when they are retrieved, to something like 'd-m-Y H:i:s' ?
You can do this with Carbon library
public function getFormattedPurchasedAttribute($date)
{
return Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('d-m-Y H:i:s');
}
You have to use carbon class. Write this line in the top where all namespace are used.
use Carbon;
I personally don't use $dateFormat attribute because it changes format for all dates fields. What I would do is creating custom accessors to get formatted fields for example:
public function getFormattedPurchasedAttribute($value) {
return $this->asDateTime($value)->format('d-m-Y H:i:s');
}
so you can now use $model-formatted_purchased to get purchased field formatted in way you want

Validate Date and Time in the Laravel Model

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));

Querying a date column with Laravel's query builder

When writing a query against a table with a date column using the Laravel query builder, what data type should be used? The following should return 13 results but instead returns nothing:
$date = new \DateTime("-2 days");
Model::whereDate($date)->get();
Dumping the query shows that laravel is trying this:
array(3) {
'query' =>
string(62) "select * from `table` where `date` = ?"
'bindings' =>
array(1) {
[0] =>
class DateTime#310 (3) {
public $date =>
string(19) "2013-10-07 14:39:11"
public $timezone_type =>
int(3)
public $timezone =>
string(3) "UTC"
}
}
'time' =>
double(5.55)
}
Writing the query as Model::whereDate($date->format("Y-m-d"))->get() instead works but doesn't seem like the Laravel way to do it.
Is there a specific object type I should be passing into the query to filter by a date column?
EDIT: The model in this example looks like this:
class Model extends Eloquent {
protected $table = 'table';
public function getDates() {
return array('date');
}
}
The table it refers to looks like this:
CREATE TABLE table(
some_field VARCHAR(255),
date DATE
) ENGINE = 'InnoDB';
Laravel thinks the date column is a string: Model::lists('date') returns an array of strings, as does DB::table('table')->lists('date').
Changing $date = new \DateTime("-2 days"); to $date = \Carbon\Carbon::now()->subDays(2) doesn't allow me to query the date column directly with the Carbon object.
UPDATED: For whatever reason, the built-in MySQL date to \Carbon\Carbon isn't working for me, so the simplest solution was to write one as a query scope:
public function scopeDate($query, \Carbon\Carbon $date) {
return $query->whereDate($date->toDateString());
}
You should add your column in the getDates() array. By doing this Eloquent will automatically convert your datetime to Carbon object.
From the docs:
By default, Eloquent will convert the created_at, updated_at, and
deleted_at columns to instances of Carbon, which provides an
assortment of helpful methods, and extends the native PHP DateTime
class.
See this:
http://laravel.com/docs/eloquent#date-mutators
Again, providing the date in the right format (Y-m-d) may still be necessary because it is not always possible to tell how to interpret a given date
As told here, Laravel uses Carbon as a DateTime class, you can perform it using:
Model::whereDate( \Carbon\Carbon::now()->subDays(2) )->get();

Categories