how can I style the date format of a date_field?
I got the following form:
<%= form_for([@user, @vehicle]) do |f| %>
<%= f.label :name, "Vehicle name" %>
<%= f.text_field :name, class: 'form-control' %>
<%= f.label :matriculation_date %>
<%= f.date_field :matriculation_date, class: 'form-control' %>
<%= f.submit "Add", class: "btn btn-primary" %>
<% end %>
this is rendering the following HTML for the date field:
<input class="form-control" type="date" name="vehicle[matriculation_date]" id="vehicle_matriculation_date">
The date field accept input in the following format: mm/dd/yyyy
. I want it to accept format like dd/mm/yyyy
.
I tried to edit it.yml file without any luck.
it:
date:
formats:
default: ! '%d/%m/%Y'
datetime:
formats:
default: ! '%d/%m/%Y %H:%M'
Any clue? Thank you
None of the proposed solutions solve my problem, so I think my question was not very clear. What I want is just to style how the date_field prompt the user (see image for more details). At the moment the form show mm/dd/yyyy
, and I want it to show dd/mm/yyyy
.
Not sure it might be a useful information, but I'm using Bootstrap for styling.
You can do:
<%= f.date_field :matriculation_date, as: :date, value: f.object.try(:strftime,"%m/%d/%Y"), class: 'form-control' %>
You can convert the date formate with strftime()
@date.strftime("%d/%m/%Y")
It will convert your date into dd/mm/yyyy
formate as you wanted.
Here I am showing you an example:
t = Time.now
=> 2016-04-28 16:09:42 -0700
>> t.strftime("%d/%m/%Y")
=> "28/04/2016"
for more strftime()
formatting options you can check this http://apidock.com/ruby/DateTime/strftime
EDIT :
After reading your comment and screenshot i've got the solution as follow.
You can also use this gem: https://github.com/Nerian/bootstrap-datepicker-rails on your gemfile.rb
gem 'bootstrap-datepicker-rails'
then bundle install and restart rails server
then add this line to app/assets/stylesheets/application.css
*= require bootstrap-datepicker
and add this line to app/assets/javascripts/application.js
//= require bootstrap-datepicker
and to use this in your form:
<%= f.date_field :matriculation_date, :id => "datepicker" %>
and add this javascript on the same view of your form
<script>
$('#datepicker').datepicker({format: 'dd/mm/yyyy'});
</script>
You can try this
@yourdate.strftime("%m/%d/%Y")
this works!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With