I using Twig in a PHP application,
The PHP object that I use has an attribute called "date", got from SQL Server.
It's look like : "Mar 2 2014 12:00:00:000AM"
I try to convert it using Twig for display it, I try with | date("Y-m-d") without success :
An exception has been thrown during the rendering of a template ("DateTime::__construct() [function.DateTime---construct]: Failed to parse time string (Jun 20 2013 12:00:00:000AM) at position 20 (:): Unexpected character") in "..." at line 96.
Any ideas ?
Thanks,
Have a nice day.
The date filter can work on \DateTime instances and strings that can be passed to strtotime(), apparently yours isn't.
You mention you're using an object that has the date property, I recommend adding a new function to it:
public function getDateAsObject()
{
// should be able to parse this format: Mar 2 2014 12:00:00:000AM
return \DateTime::createFromFormat("M j Y h:i:s:uA", $this->date);
}
You may need to adapt the format and the functions name for your conventions.
You can use it in your template:
{{ your_object.dateAsObject|date("Y-m-d" }}
You don't need to use date('Y-m-d'), base on the error message your object's date attribute is a type of DateTime, so use following:
// I assume 'object' is your object which has 'date' as the attribute
<span>Date: </span>{{ object->date->format('Y-m-d') }}
Check documentation for DateTime::Format
Related
in my controller i used Carbon to get current timestamp like showing below:
$current_timestamp = Carbon::now()->format('j/n/Y');
the output of the above:
18/8/2022
and i am getting data from external API like showing below (from blade):
$data[0]['DocDate']
the output of the above:
18/8/2022 12:00:00 AM
now i want to remove 12:00:00 AM from it
i tried in blade view to do:
{{Carbon\Carbon::parse($data[29]['DocDate'])->toDateString()}}
but i am getting this error:
Could not parse '18/8/2022 12:00:00 AM': Failed to parse time string (18/8/2022 12:00:00 AM) at position 0 (1): Unexpected character
and i tried:
$data[29]['DocDate']->format('j/n/Y')
and i get this error:
Call to a member function format() on string
how can i overcome this issue?
You can use create from format function to change the format of incoming date as below:
$inDate = $data[0]['DocDate'];
$outDate = Carbon::createFromFormat('d/m/Y h:i:s a', $inDate )->format('d/m/Y');
On the principle of Keep It Simple - Why not just compare them as strings?, the longer one can easily be shortened, then just compare.
Accepted this is not a "purest" approach, but the format of a "standard" date is not likely to change.
now i want to remove 12:00:00 AM from it
So you don't actually care about date, you don't need Carbon or parsing according to format, you just need to keep the first word of your string:
{{ explode(' ', $data[0]['DocDate'])[0] }}
I'm trying to convert this:
{{ "26/03/2013"|date("d/m/Y") }}
in Twig but its is throwing the error
Uncaught Exception: DateTime::__construct(): Failed to parse time
string (26/03/2013) at position 0 (2): Unexpected character in
/home/vagrant/Code/Phantom
Website/vendor/twig/twig/lib/Twig/Template.php on line 218.
If I pass this:
{{ "03/26/2013"|date("m/d/Y") }}
It works, so I imagine I need to change something related to Twigs date formatting
The date filter is about formatting DateTime Object, so if you pass a string this will be passed to the constructor of the DateTime object then to the format method, so in your case, you need to format the string that looks good for a DateTime constructor as example
{{ "2013-3-26"|date("d/m/Y") }}
From the doc:
The format specifier is the same as supported by date, except when the
filtered data is of type DateInterval, when the format must conform to
DateInterval::format instead.
And also about string format:
The date filter accepts strings (it must be in a format supported by
the strtotime function), DateTime instances, or DateInterval
instances. For instance, to display the current date, filter the word
"now":
Try this in this twigfiddle
If you use /'s as delimiter the expected format is m/d/Y,
To pass the date as day, month, year you need to use a - as delimiter
{{ "26-03-2017" | date('d/m/Y') }}
fiddle
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"!
In the database, I have following date: 1924-01-17, as a date-type, but when I render it as {{ person.BirthDate | date("d/m/Y") }}, it gives as a result 17/01/2024.
How can I solve the Year-problem?
Twig documentation for date says:
The date filter accepts strings (it must be in a format supported by
the strtotime function), DateTime instances, or DateInterval
instances.
DateTime instance should do the trick, and based on comments it fixed this.
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.