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"!
Related
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
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"
Take this example:
{{ $article->created_at->format('M') }}
It returns Nov. I need to localise this to my language, so the output should be Kas
Thought about doing the following:
{{ trans("language.{$article->created_at->format('M')}") }}
app/lang/tr/language.php -> 'nov' => 'kas'
This looks like reinventing the wheel and programmatically pretty terrible. I'm sure there are some localisation standards. Something like:
{{ $article->created_at->format('M')->localiseTo('tr_TR') }}
What's the best way to achieve this?
Using a library as Laravel-Date you will just need to set the language of the app in the Laravel app config file and use its functions to format the date as you want.
Set the language in /app/config/app.php
'locale' => 'es',
I've found this library pretty useful and clean. To use it, you can write something like the example in the library readme file. I leave the results in spanish.
echo Date::now()->format('l j F Y H:i:s'); // domingo 28 abril 2013 21:58:16
echo Date::parse('-1 day')->diffForHumans(); // 1 día atrás
This is the link to the repository:
https://github.com/jenssegers/laravel-date
To install this library you can follow the instructions detailed in the following link:
https://github.com/jenssegers/laravel-date#installation
When you retrieve a date off a model in Laravel, you get back a Carbon object:
https://github.com/briannesbitt/Carbon
If you refer to the Carbon documentation, it tells you how you can get a locale formatted Date:
Unfortunately the base class DateTime does not have any localization
support. To begin localization support a formatLocalized($format)
method has been added. The implementation makes a call to strftime
using the current instance timestamp. If you first set the current
locale with setlocale() then the string returned will be formatted in
the correct locale.
setlocale(LC_TIME, 'German');
echo $dt->formatLocalized('%A %d %B %Y'); // Donnerstag 25 Dezember 1975
setlocale(LC_TIME, '');
echo $dt->formatLocalized('%A %d %B %Y'); // Thursday 25 December 1975
So basically, just use formatLocalized('M') instead of format('M')
As of carbon version 2.30.0, you can use the translatedFormat function
$date = Carbon::parse('2021-12-08 11:35')->locale('pt-BR');
echo $date->translatedFormat('d F Y'); // 08 dezembro 2021
It is also a good idea to set locale globally for each request (eg. in filters.php) when using Carbon date instances.
App::before(function($request) {
setlocale(LC_TIME, 'sk_SK.utf8');
});
and then proceed as usual
$dt->formatLocalized('%b'); // $dt is carbon instance
See format options here and list of locales here.
In addition to the accepted answer, I was looking for a way to use this within Blade using the Carbon instance of created_at for example. The class in the accepted answer didn't seem to accept a Carbon instance as date, but rather parsed a date from a string.
I wrote a little helper function to shorten the code in the blade templates:
function localeDate($date, $format)
{
return Jenssegers\Date\Date::createFromFormat('d-m-Y H:i:s', $date->format('d-m-Y H:i:s'))->format($format);
}
Within Blade you can now use:
{{ localeDate($model->created_at, 'F') }}
Which would return the fully written name of the month in the locale set in config/app.php
If there's a better way (or I missed something in the code), please let me know. Otherwise this might be helpfull for others.
Goto your App->Config->app.php
put
'timezone' => 'Asia/Kolkata',
use simple {{$post->created_at->diffForHumans()}}
Localized (i18n) date with Laravel 8
In Laravel 8, I added a method in my Block Model:
use Illuminate\Support\Carbon;
class Block extends Model
{
public function updatedDate() {
return Carbon::parse($this->updated_at)->translatedFormat('d F Y');
}
}
In my Blade template, I want to get the latest row's update date:
{{ $blocks->last()->updatedDate() }} // prints out 25 January 2022
// PS. Carbon uses your app.locale config variable so setting locale() is optional
// return Carbon::parse($this->updated_at)->locale('en')->translatedFormat('d F Y')
I guess you should consult setlocale manpage. Though Im not sure if Laravel has any wrapper on it.
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.
I want to input a timestamp in below format to the database.
yyyy-mm-dd hh:mm:ss
How can I get in above format?
When I use
$date = new Zend_Date();
it returns month dd, yyyy hh:mm:ss PM
I also use a JavaScript calender to insert a selected date and it returns in dd-mm-yyyy format
Now, I want to convert these both format into yyyy-mm-dd hh:mm:ss so can be inserted in database. Because date format not matching the database field format the date is not inserted and only filled with *00-00-00 00:00:00*
Thanks for answer
Not sure if this will help you, but try using:
// to show both date and time,
$date->get('YYYY-MM-dd HH:mm:ss');
// or, to show date only
$date->get('YYYY-MM-dd')
Technically, #stefgosselin gave the correct answer for Zend_Date, but Zend_Date is completely overkill for just getting the current time in a common format. Zend_Date is incredibly slow and cumbersome to use compared to PHP's native date related extensions. If you don't need translation or localisation in your Zend_Date output (and you apparently dont), stay away from it.
Use PHP's native date function for that, e.g.
echo date('Y-m-d H:i:s');
or DateTime procedural API
echo date_format(date_create(), 'Y-m-d H:i:s');
or DateTime Object API
$dateTime = new DateTime;
echo $dateTime->format('Y-m-d H:i:s');
Don't do the common mistake of using each and every component Zend Frameworks offers just because it offers it. There is absolutely no need to do that and in fact, if you can use a native PHP extension to achieve the same result with less or comparable effort, you are better off with the native solution.
Also, if you are going to save a date in your database, did you use any of the DateTime related columns in your database? Assuming you are using MySql, you could use a Timestamp column or an ISO8601 Date column.
This is how i did it:
abstract class App_Model_ModelAbstract extends Zend_Db_Table_Abstract
{
const DATE_FORMAT = 'yyyy-MM-dd';
public static function formatDate($date, $format = App_Model_ModelAbstract::DATE_FORMAT)
{
if (!$date instanceof Zend_Date && Zend_Date::isDate($date)) {
$date = new Zend_Date($date);
}
if ($date instanceof Zend_Date) {
return $date->get($format);
}
return $date;
}
}
this way you don't need to be concerned with whether or not its actually an instance of zend date, you can pass in a string or anything else that is a date.
a simple way to use Zend Date is to make specific function in its business objects that allows to parameter this function the date format. You can find a good example to this address http://www.pylejeune.fr/framework/utiliser-les-date-avec-zend_date/
this is i did it :
Zend_Date::now->toString('dd-MM-yyyy HH:mm:ss')
output from this format is "24-03-2012 13:02:01"
and you can modified your date format
I've always use $date->__toString('YYYY-MM-dd HH-mm-ss'); method in the past but today didn't work. I was getting the default output of 'Nov 1, 2013 12:19:23 PM'
So today I used $date->get('YYYY-MM-dd HH-mm-ss'); as mentioned above. Seems to have solved my problem.
You can find more information on this on output formats here: http://framework.zend.com/manual/1.12/en/zend.date.constants.html