Laravel4 - handling date format between whole application and mysql - php

In laravel 4 i have lots of database fields that having date type and datetime . but i am need to show date format like dd/mm/yy H:i:s like any format and also have to handle date formation on insertion and update. Is they any way to get works in one place?

Yes you can do that, by creating mutator method in your model; for example, if you have a Post model and has a date_of_birth property and you want to set the date in yyyy/mm/dd H:i:s but user is probably providing the date in a different format. In this case crate a mutator method in the Post model like this:
public function setDateOfBirthAttribute($value)
{
// value will be the given date by user
$dt = \Carbon\Carbon::createFromFormat('Y/m/d H:i:s',$value)->toDateString();
$this->attributes['date_of_birth'] = $dt;
}
To access the date just create an accssor method like:
public function getDateOfBirthAttribute()
{
return \Carbon\Carbon::createFromFormat('d-m-Y H:i:s', $this->date_of_birth);
}
Now the date_of_birth will be inserted using the format that you have used in the mutator method and when you'll show that date, it'll be displayed using the format that you have used in the accessor method. You may also check the Date Mutators.

A must have package for dates is Carbon. Take a look at the documentation on GitHub: https://github.com/briannesbitt/Carbon

Related

Laravel saving data with Carbon::now() is formatted differently to created_at

I'm working with a Laravel project and time zones (I know time zones are a pain), and what's occurred to be is that one of my custom columns in my table, the column called last_checked which is stored as a timestamp appears to be formatted differently from the created_at, and it means that my time zone parsing isn't parsing the date at all for the user's time zone.
Here's what I mean...
When storing a record, I set the date and time:
$uptimeMonitor = Monitors::where('id', $monitor['id'])
->get()
->first();
$uptimeMonitor->last_checked = Carbon::now();
$uptimeMonitor->save();
But when I retrieve the result, looking in my network request, I'm seeing this format:
2021-04-05 11:46:54
But when I look at both the created_at and updated_at columns, they're in this format:
2021-04-05T10:01:16.000000Z
So the question here is, what am I doing wrong with saving my data? Both formats seem to be visually shown the same in the database, but for some strange reason, the first example isn't parsing correctly.
Carbon uses the default DateTime PHP object, so use the date_default_timezone_set() function, for example: date_default_timezone_set('UTC');
or you define it AppServiceProvider App/Providers/AppServiceProvider.php
public function boot()
{
date_default_timezone_set('UTC');
}
Or you can use setTimezone of carbon method
echo Carbon::now()->setTimezone('UTC')->format('H:i');
Try this
$uptimeMonitor = Monitors::where('id', $monitor['id'])
->get()
->first();
$uptimeMonitor->last_checked = Carbon::now()->setTimezone('UTC')->format('Y-m-d H:i:s');
$uptimeMonitor->save();
Note my default app timezone is UTC just find your default timezone
and set it in `setTimezone('UTC');
You need to add all the datetime properties in your $casts model protected member:
https://laravel.com/docs/8.x/eloquent-mutators#date-casting
All is OK in your DB, it's just Laravel model has to know it's a date to format with the full ISO-8601 string in your JSON.
Side note, you still should have "UTC" as your default in config/app.php, it does not prevent from having any timezone handling for particular cases, or to handle users timezone, on the contrary.
If your dates output string as GMT+1 by default, it's very likely a configuration mistake.

Laravel Date Format in Table

I am trying to edit the Migration in laravel so that the birth date gets the format needed. Now I have searched around on forums, and none get to my problem (that or I am stupid)
The format used in the code below does not seem to work, because I get errors on the dd part of the format. I've tried a couple of solutions, including editing the model to re-format the date, but that did nothing.
$table->date(dd, mm, YY)('birth_date');
You should use this in your migration:
$table->date('birth_date');
Dates are always stored in the same format in the database. For example, the MySQL documentation on the DATE datatype says:
The supported range is '1000-01-01' to '9999-12-31'.
It is for your application to change the dates into a format you desire. There are different ways to achieve this. In your views you could use format():
{{ $user->birth_date->format('dd, mm, YY') }}
// or if birth_date can be NULL:
{{ optional($user->birth_date)->format('dd, mm, YY') }}
As an alternative, you could use an Accessor in your model:
public function getBirthDateAttribute($date)
{
if (is_null($date)) {
return null;
} else {
return Carbon::parse($date)->format('dd, mm, YY');
}
}
When you set the dateFormat property, you are defining the format for how dates are stored in the database and how they are formatted when your model is serialized.
When you access your birthdate attribute on the model, you are still going to be given a carbon instance that can be used to format the birthdate in any way you would like.
Note that dateFormat will also change the format for your birth_date attributes.
Also Declare in the model:
class ModelName extends Model
{
protected $casts = [
'birth_date' => 'datetime:d/m/Y', // Change your format
];
}
$table->date('birth_date');
you can save data here format (Y-m-d) like (2019-12-31)
Then when You get this you can show your desire format.
other way,If you think
$table->string('birth_date');
Then save data format (Y-m-d) like (2019-12-31).
When You try to show data your desire format just use Carbon\Carbon & format your date

How to change DateTime format to a desired format via Carbon laravel

I'm using laravel 5.5 and Carbon library to write an API.
I store all date and time values in MySQL database as common YYYY-MM-DD HH:MM:SS format.
But on the other hand front-end developer ask me to return all dates as 2017-12-20T20:30:00.000Z. seems that is a common format in JavaScript.
Is there any way to convert all DateTime formatted fields to desired format via laravel or Carbon ?
Update:
First problem is solved but another one is that client want to send date times as same 2017-12-20T20:30:00.000Z for all fields of table. while I should get and save them as common DateTime. What can I do in this case?
Javascript uses ISO 8601 syntax. In PHP, you can use like this:
date('c', strtotime($yourDateTime)); // c is ISO 8601 format
Reference here:
Since the date is casting as Carbon, use format():
$date->format($desiredFormat);
The list of characters for creating $desiredFormat will also be helpful.
Laravel Provide getter and setter method for format Eloquent attribute values
by default laravel return 'dateTime' as carbon instance
so, you can change format in model using getter method
public function getDateTimeAttribute($value)
{
$desiredFormat = "Y-M-d"; //change format as per your requirement
$value->format($desiredFormat);
}
Link for more about getter and setter method
https://laravel.com/docs/5.5/eloquent-mutators
{{ date('M j, Y h:ia', strtotime($created_at)) }}
It gives us like "Dec 30, 2017 16:39am"
You can edit you date time of course(M j, Y h:ia) just google it "php: date - manual"

Date from API call not being accepted in Laravel as a dateTime field

I am getting dates from an API call. The date is formatted in this way
2017-10-19T15:30:00
I want to store this date in my MYSQL database using Laravel Database Migration, currently I am using
$table->dateTime('datetime');
When I store it using a dateTime field as above, all I get is
0000-00-00 00:00:00
When I use a timestamp format, I don't get accurate dates, I just get the current time and date.
How can I solve this? Any help would be appreciated, and please let me know if you want further information.
Luckily, Laravel uses the Carbon class, which makes things a lot easier to modify dates. In your case, you want to do this:
Carbon::createFromFormat('Y-m-d\TH:i:s', $date);
There are two ways you can implement it: you can modify it before you save it to your database, or you can add a mutator on your model.
public function setDatetimeAttribute($value)
{
$this->attributes['datetime'] = Carbon::createFromFormat('Y-m-d\TH:i:s', $value);
}
You may want to build in some validation to see which format the date/time is in before you try to convert it.
in the model you should put:
protected $dates = ['datetime'];
Use Carbon
$dt = Carbon::parse('1975-05-21 22:23:00.123456');
to save:
$model = new Model;
$model->date = $dt; // you can use the carbon object directly
$model->save();

Laravel format datetime

I have in my database the date of birth of a user, but I want to format that to something like 27 March 2000. I already have the date of registered and I can format that, but if I try to format the date of birth it gives me the following error:
Call to a member function format() on string
This code I used to show and format the date of birth of a user:
{{ucfirst(Auth::user()->created_at->format("M d Y"))}}
I tried to use this code for the date of birth because it is in a table with all the users:
{{ucfirst($user->birthdate->format("M d Y"))}}
This is the database structure:
http://i.stack.imgur.com/Agchg.png
You need to tell Laravel that your birthdate field is a date, otherwise Laravel will just fetch it as-is and not touch it at all. You do that by adding a protected $dates to the model-class which is an array of all fields which Laravel should treat as dates.
class MyModel extends [...] {
protected $dates = ['bithdate'];
}
This will tell Laravel that birthdate is a date and Laravel will convert it to a instance of Carbon.

Categories