I would like to set Laravel and Carbon so that, based on the current locale selected by the user, dates will be formatted with the correct pattern. I thought it was enough to set LC_TIME on the desired locale and then use the Carbon method toDateString to get the correct format but, regardless the LC_TIME setted, it always return a date string in the format yyyy-mm-dd.
Expected results:
- If Italian selected, then mm/dd/yyyy
- If English selected, then yyyy-mm-dd
- and so on
I'm using Laravel 5.5 and Carbon 1.36.1
Carbon::now()->isoFormat('L');
Gives you the current standard digit-format date for the current locale (20/5/2020 for "it_IT", 5/20/2020 for "en_US").
And you can customize this format for a given locale in translations:
Translator::get('en')->setTranslations([
'formats' => [
'L' => 'YYYY-MM-DD',
],
]);
Recently I had the same problem with an old Laravel app and we solved it by storing the format of the localised dates in a separate language file:
resources/lang/en/dates.php
return [
'full' => 'Y-m-d'
];
resources/lang/it/dates.php
return [
'full' => 'm/d/Y'
];
When formatting a date, just use the config() helper to fetch the format provided for the language set in config/app.php, use $date->format(trans('dates.full')) and it will return the proper localised date.
If you so fancy you can use a macro (which was added in 1.26.0) too, to simplify this process:
Carbon::macro('localisedFormat', function ($key) {
return $this->format(trans("dates.{$key}"));
});
and access it via
$date->localisedFormat('full');
Related
I have been trying to get the the Year and Month from the user and insert them into the database.
i am using input type month so that the user can send only the Year and the Month.
<input type="month" name="date_from"/>
<input type="month" name="date_to"/>
and this is my model
function setDateFromAttribute($value)
{
$this->attributes['date_from'] = \Carbon\Carbon::createDateFromFormat('Y-m', $value);
}
function setDateToAttribute($value)
{
$this->attributes['date_to'] = \Carbon\Carbon::createDateToFormat('Y-m', $value);
}
protected $fillable = [
'date_from',
'date_to',
];
and data is saved as 0000.00.00
the data type in my database for these two inputs is
timestamp
i do not know what i am doing wrong here. please help
I don't see createDateFromFormat as a valid Carbon method in the documentation https://carbon.nesbot.com/docs/
Likewise, there does not appear to be any createDateToFormat method.
Carbon::createFromFormat() returns a Carbon object, not a string or equivalent MySQL timestamp, so, assuming you change your code to be:
$this->attributes['date_from'] = \Carbon\Carbon::createFromFormat('Y-m', $value)->toDateTimeString();
It should provide the results you are looking for.
References:
Converting a carbon date to mysql timestamp.
#Ted Stresen-Reuter
Sorry for the late reply couldn't find a solution that works within the model. tried your method which i have tried before with minor changes.
thanks a lot for trying to help me.. i found a method to complete this inside the controller which i will not recommend, but this was the best i was able to find which works and i was on a tight schedule.
'date_from' => isset($date_from[$key]) ? date('Y-m-d h:i:s', strtotime($date_from[$key])) : '',
'date_to' => isset($date_to[$key]) ? date('Y-m-d h:i:s', strtotime($date_to[$key])) : '',
the type timestamp accepts at least dates in full formats. as i know how i pass the data from blade to the controller i was able to add a date method and within it a strttotime method to convert my YY-MM into YY-MM-DD and the date that is inserted by default will be 01.
I store in my database a date format like this:
2017-02-22 16:55:40
I added it to my database like this:
Carbon::now();
I need to check if 4 hours passed since this date.
How I can do this? I couldn't figure out how I can convert this format into Carbon or timestamp.
If you are using Laravel and the date is a Carbon instance from a Model you have access to the whole Carbon API.
You can use the Difference API of Carbon for this specific purpose.
echo $model->thedate->diffInHours($now, false);
If your model does not threat the date as a carbon instance you can cast it by adding the date to the dates array of the current model like so
protected $dates = [
'field_name',
];
Check out Date casting for more information
Update with an explicit example
$user = User::first();
// This will return the difference in hours
$user->created_at->diffInHours(Carbon\Carbon::now(), false);
You can convert it to a Carbon object with:
Carbon::parse('2017-02-22 16:55:40');
How to save date in GTM 0 in database?
I mean this: protected $dates = ['created_at'];
I'd personally recommend leaving/setting the timezone in your app config as UTC rather than GMT:
https://www.timeanddate.com/time/gmt-utc-time.html
To make sure my custom date fields are stored correctly I use a modifier on my model class like so:
public function setStartAtAttribute($date)
{
$timezone = (Auth::check() ? Auth::user()->profile->timezone : config('pgn.phoenix.timezone'));
$tzdate = Carbon::createFromFormat('d/m/Y H:i', $date, $timezone);
$this->attributes['start_at'] = $tzdate->timezone('UTC');
}
That would need use Carbon\Carbon; adding to the top of your model too.
That config param above is set to 'Europe/London' and is the timezone that our guests are shown dates, (works with daylight savings) whilst not affecting the 'system' timezone.
You can change the timezone of the application by going to the config/app.php file and changinf the following line:
'timezone' => 'GMT'
If your dates are still saved in a different timezone, it is likely that the server datetime will need to be altered to GMT. This can be done using the following command and following the instructions:
dpkg-reconfigure tzdata
I am using laravel 5.0. I am getting data from controller as json. I am having value like this.
{"timstamp_date":"1434360957"},
I need to convert this unix timestamp value as Normal Date Like (15-06-2015) or (15-March-2015).
I have used Date(timstamp_date) but it is showing current time only. Not my timstamp date
You could use:
date("d-m-Y H:i:s", 1434360957);
EDIT
You could try;
var dateTime = new Date(1434360957*1000);
var formatted = dateTime.toGMTString();
https://jsfiddle.net/sp57Lnpf/
Use the date function. You need to specify the format as the first parameter:
date("d-m-Y", $timestamp_date)
http://php.net/manual/en/function.date.php
Laravel also comes with Carbon you could use that if you wanted to for further manipulation of the data if you so required it.
http://carbon.nesbot.com/docs/
Whenever I use the trans() function to return a specific translation from the validation.php file, it works just perfectly. I have two languages in my application and the translations get returned for both of them.
However, whenever I use the Laravel validator, it returns messages in the default locale only. Is there something I need to specify in the validator? How do I make it work for both languages?
You need to pass as 3rd parameters your translations. Let's assume you have defined your fields, rules and validator like in the following code:
$data = Input::only('title');
$rules['title'] = 'required|min:20|max:80',
$validator = Validator::make($data, $rules,
Lang::get('forms.validation.entry'));
Now you need to define your translations. Let's assume you need translation for fr lang so you need co create lang/fr/forms.php file and put the following content into it:
<?php
return
array (
'validation' => array (
'entry' => array (
'title.required' => 'Your translation for title required',
'title.min' => 'Your translation for title min',
'title.max' => 'Your translation for title max',
)
)
);
Of course you can create file with simpler array but it's just example - instead of forms.validation.entry it could be for example just forms or validation.
The problem originated from my localization implementation. I've added App::setLocale(Session::get('lang')); to the App::before() method in the filters.php file and it all works now.
in resources/lang/en folder laravel have validation.php. When you create new language so you can copy this file to new created language folder and then edit it to this language.
for example you wanna create fr language
.
/resources/lang/fr/validation.php and translate it to this language