Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the default date and time format in Rails 4

I was looking for a way to change the default date format in Rails 4.

like image 297
smile2day Avatar asked Jul 26 '13 00:07

smile2day


People also ask

How do I change the date format in Ruby on Rails?

You need to convert your string into Date object. For that, use Date#strptime . You can use Date#strftime to convert the Date object into preferred format.

What is the default format for date and time?

The default date format shows as YYYY-MM-DD.

What is the default date format in R?

Note that the default date format is YYYY-MM-DD; therefore, if your string is of different format you must incorporate the format argument. There are multiple formats that dates can be in; for a complete list of formatting code options in R type ? strftime in your console.

How do I change the default date format in laravel?

So, let's add these variables to config/app. return [ 'date_format' => 'm/d/Y', 'date_format_javascript' => 'MM/DD/YYYY', ]; And then, in Laravel, we can use this: Carbon::createFromFormat(config('app. date_format'), $value)->format('Y-m-d'); Carbon::parse($value)->format(config('app.


2 Answers

Found a nice approach through the Rails Internationalization (I18n) API

Data and time formats can be 'translated' by adding the format to the i18n configuration.

config/locales/en.yml

en:   date:     formats:       default: "%d/%m/%Y"   time:     formats:       default: "%d/%m/%Y %H:%M" 

Note: remember to not have tabs for the indent, like I did first time :)


As mentioned by NoelProf in the comments

To use i18n conversion don't forget the l (lower case L) before your date in views! For example: <%= l your_date %>

You are invited to comment if you found other ways working well.

like image 104
smile2day Avatar answered Oct 05 '22 18:10

smile2day


Add this

# Date Date::DATE_FORMATS[:default] = "%d/%m/%Y"   # Time Time::DATE_FORMATS[:default] = "%d/%m/%Y %H:%M"  

to config/initializers/date_time.rb

Then restart the server.

like image 21
732 Avatar answered Oct 05 '22 17:10

732