Laravel Date Format in Table - php

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

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.

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

change the date format in laravel view page [duplicate]

This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 12 months ago.
I want to change the date format which is fetched from database.
now I got 2016-10-01{{$user->from_date}} .I want to change the format 'd-m-y' in laravel 5.3
{{ $user->from_date->format('d/m/Y')}}
Try this:
date('d-m-Y', strtotime($user->from_date));
It will convert date into d-m-Y or whatever format you have given.
Note: This solution is a general solution that works for php and any of its frameworks. For a Laravel specific method, try the solution provided by Hamelraj.
In Laravel use Carbon its good
{{ \Carbon\Carbon::parse($user->from_date)->format('d/m/Y')}}
In your Model set:
protected $dates = ['name_field'];
after in your view :
{{ $user->from_date->format('d/m/Y') }}
works
You can check Date Mutators: https://laravel.com/docs/5.3/eloquent-mutators#date-mutators
You need set in your User model column from_date in $dates array and then you can change format in $dateFormat
The another option is also put this method to your User model:
public function getFromDateAttribute($value) {
return \Carbon\Carbon::parse($value)->format('d-m-Y');
}
and then in view if you run {{ $user->from_date }} you will be see format that you want.
There are 3 ways that you can do:
1) Using Laravel Model
$user = \App\User::find(1);
$newDateFormat = $user->created_at->format('d/m/Y');
dd($newDateFormat);
2) Using PHP strtotime
$user = \App\User::find(1);
$newDateFormat2 = date('d/m/Y', strtotime($user->created_at));
dd($newDateFormat2);
3) Using Carbon
$user = \App\User::find(1);
$newDateFormat3 = \Carbon\Carbon::parse($user->created_at)->format('d/m/Y');
dd($newDateFormat3);
Method One:
Using the strtotime() to time is the best format to change the date to the given format.
strtotime() - Parse about any English textual datetime description into a Unix timestamp
The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.
Example:
<?php
$timestamp = strtotime( "February 26, 2007" );
print date('Y-m-d', $timestamp );
?>
Output:
2007-02-26
Method Two:
date_format() - Return a new DateTime object, and then format the date:
<?php
$date=date_create("2013-03-15");
echo date_format($date,"Y/m/d H:i:s");
?>
Output:
2013/03/15 00:00:00
You can use Carbon::createFromTimestamp
BLADE
{{ \Carbon\Carbon::createFromTimestamp(strtotime($user->from_date))->format('d-m-Y')}}
I had a similar problem, I wanted to change the format, but I also wanted the flexibility of being able to change the format in the blade template engine too.
I, therefore, set my model up as the following:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
\Carbon\Carbon::setToStringFormat('d-m-Y');
class User extends Model
{
protected $dates = [
'from_date',
];
}
The setToStringFormat will set all the dates to use this format for this model.
The advantage of this for me is that I could have the format that I wanted without the mutator, because with the mutator, the attribute is returned as a string meaning that in the blade template I would have to write something like this if I wanted to change the format in the template:
{{ date('Y', strtotime($user->from_date)) }}
Which isn't very clean.
Instead, the attribute is still returned as a Carbon instance, however it is first returned in the desired format.
That means that in the template I could write the following, cleaner, code:
{{ $user->from_date->format('Y') }}
In addition to being able to reformat the Carbon instance, I can also call various Carbon methods on the attribute in the template.
There is probably an oversight to this approach; I'm going to wager it is not a good idea to specify the string format at the top of the model in case it affects other scripts. From what I have seen so far, that has not happened. It has only changed the default Carbon for that model only.
In this instance, it might be a good set the Carbon format back to what it was originally at the bottom of the model script. This is a bodged idea, but it would work for each model to have its own format.
Contrary, if you are having the same format for each model then in your AppServiceProvider instead. That would just keep the code neater and easier to maintain.
I suggest using isoFormat for better appearance on the web pages.
{{ \Carbon\Carbon::parse($blog->created_at)->isoFormat('MMM Do YYYY')}}
The result is
Jan 21st 2021
Carbon Extension
In Laravel 8 you can use the Date Casting: https://laravel.com/docs/8.x/eloquent-mutators#date-casting
In your Model just set:
protected $casts = [
'my_custom_datetime_field' => 'datetime'
];
And then in your blade template you can use the format() method:
{{ $my_custom_datetime_field->format('d. m. Y') }}
In Laravel you can add a function inside app/Helper/helper.php like
function formatDate($date = '', $format = 'Y-m-d'){
if($date == '' || $date == null)
return;
return date($format,strtotime($date));
}
And call this function on any controller like this
$start_date = formatDate($start_date,'Y-m-d');
Hope it helps!
For a more natural date format used everywhere outside of the US, with time that includes hours, minutes and seconds:
07/03/2022 19:00:00
{{ \Carbon\Carbon::parse($transaction->created_at)->format('d/m/Y H:i:s')}}
Or if you'd prefer to use a more natural 12-hour-clock-based time format like this:
07/03/2022 7:00:00 PM
{{ \Carbon\Carbon::parse($transaction->created_at)->format('d/m/Y g:i:s A')}}
Here's the full list of variables available for use in the PHP/Carbon date-time format.
Sometimes changing the date format doesn't work properly, especially in Laravel. So in that case, it's better to use:
$date1 = strtr($_REQUEST['date'], '/', '-');
echo date('Y-m-d', strtotime($date1));
Then you can avoid error like "1970-01-01"!

Laravel4 - handling date format between whole application and mysql

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

PHP using Laravel 4 and Carbon will not print out a DateTime field from my Database

I am building a PHP application with Laravel 4.
I am getting errors when I try to print out a DateTime record from the Database though.
{{ $user->created_at }}
Gives me this error
InvalidArgumentException
Trailing data
open: E:\Server\htdocs\projects\timeclock\www\vendor\nesbot\carbon\src\Carbon\Carbon.php
Very frustrating!
An example value from that Database field is: 2013-08-31 20:50:25.
You are missing the milisecond data on the time stamp, you need to use:
Carbon::createFromFormat('Y-m-d H:i:s.u', $value)->format('d/m/Y H:i:s');
You have to format it:
{{ $user->created_at->format('h:i:s') }}
The PHP docs has a list of all the codes available to use as a format.
I have the same issue.
And I found that this is caused by my timestamp data in database.
2013-12-13 22:40:50.561709 <- this one will cause the issue.
2013-12-13 22:40:50 <- this one will not.
Timestamp value with millisecond causes this issue.
Column which is converted to Carbon object can not have millisecond timestamp.(default: created_at, updated_at).
http://readouble.com/laravel/4/2/0/en/eloquent.html#date-mutators
If Carbon Object is not necessary, you can disallow auto-converting.
class SomeModel extends Eloquent {
public function getDates()
{
return array();
}
}
But it also make Carbon methods(ex:->format()) unavailable. You have to format timestamps in other way.

Categories