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
EDIT
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!
My answer is based on #Dharmesh_Rupani answer
Follow the steps to add the gem 'bootstrap-datepicker-rails'
I made two little changes on the form
<%= f.text_field : matriculation_date, :placeholder => 'dd/mm/yyyy', class: 'form-control datepicker' %>
The first thing is I changed the type of the field to text, because when I implemented I had two calendars, one from the date_field and another from the new gem
The other thing I changed is instead of :id I used :class, because it may happen that you have more than one date field
lastly, you should add this on the view
<script>
$( document ).ready(function() {
$('.datepicker').datepicker({format: 'dd/mm/yyyy'});
});
</script>
Related
Me and my co-workers were testing my web app. And, in the form in my computer/local/dev and server/production it shows the date format dd/mm/yyyy 00:00 and for my coworkers mm/dd/yyyy 00:00 am/pm with the same local chrome settings and computer settings.
why is this?
and how can I change this for all users? if possible.
piece of code:
<div class="mini_jumbotron">
<div class="mini_text">Inicio<%= image_tag("calendar.png", :class => "calendar")%>
</div> <br>
</div>
<%= f.datetime_field :Inicio %>
Try below code:
<%= f.date_field :Inicio, as: :date, value: f.object.try(:strftime,"%d/%m/%Y"), class: 'form-control' %>
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 :Inicio, :id => "datepicker" %>
and add this javascript on the same view of your form
<script>
$('#datepicker').datepicker({format: 'dd/mm/yyyy HH:MM:ss'});
</script>
I've got a little Rails app that I need to use the 24-hour clock for inputting times. Right now, I've got:
<div class=".col-md-7">
<%= f.label :backinservice %><br>
<%= f.time_field :backinservice %>
</div>
Which gives an AM/PM option. When I input a time like 18:56, it automagically converts it to 06:56 PM. Normally that would be totally ok, just not in this app.
I also tried:
<div class=".col-md-7">
<%= f.label :recieved %><br>
<%= f.time_field :recieved, :format=>"%H:%M" %>
</div>
But that doesn't work either.
Is there a :format option that allows for straight use of the 24-hour clock?
You have to pass the format using value key.
<div class=".col-md-7">
<%= f.label :recieved %><br>
<%=
f.time_field :recieved,
value: "%H:%M",
min: 'hh:mm:ss',
max: 'hh:mm:ss'
%>
</div>
The doc says:
The default value is generated by trying to call strftime with “%T.%L” on the objects's value. It is still possible to override that by passing the “value” option.
I had to do the following to get this to work for me:
<%=
f.time_field :my_time_field,
value: f.object.my_time_field.strftime("%H:%M")
%>
Found this out by looking at the definition of time_field, that is only creating a new instance of Tags::TimeField.new
In turn Tags::TimeField.new only does one thing which is to define the format.
I am trying to implement the country_select gem (gem 'country_select','~> 2.1.0') in a Rails 4 app without success. This is the code in my form. I have tried several permutations of this from similar questions on stack without success. I don't understand why I am getting the error -
"undefined method `input' for ActionView::Helpers::FormBuilder:0x007fafb5878c48>"
Bear in mind that I am a Rails beginner.
<%= form_for(#user, html: { multipart: true }) do |f| %>
<%= f.label :country %><br>
<%= f.input :country, as: :country %>
<%= f.submit "Update my account", class: "btn btn-primary" %>
<% end %>
I have also tried
<%= f.label :country %>
<%= f.country_select :country %>
from the documentation. 'country' is one of my user attributes.
Any guidance would be welcome on the newbie problem.
I have just spent an hour on the same problem and am annoyed at the brevity of the github documentation. Nevertheless, this worked for me and it sounds like what you need:
<%= f.country_select(:country, {selected: #user.country}, {class: "form-control"}) %>
I couldn't get the second parameter (see https://github.com/stefanpenner/country_select) to work - it gave me an error every time I tried to add anything else before the {selected...}.
<%= f.country_select :country, {priority_countries: ["SG", "US"], include_blank: "select country"}, class: 'form-control' %>
This worked for me, the first :country is an attribute of user, all the options of country_select gem will come as the next parameter and the last param will take the class name and other format features.
If the param contains a single field it can be passed with or without brackets.
I am using bootstrap-datepicker.js and it is working fine.
<div class="well">
<div id="dp5" class="input-append date" data-date-format="dd-mm-yyyy" data-date="12-02-2012">
<input class="span2" type="dp5" readonly="" value="12-02-2012" size="16">
<span class="add-on">
<i class="icon-th"></i>
</span>
</div>
</div>
I want to use it in my form in rails which is of such type
<%= simple_form_for(#customer) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :name %>
<%= f.input :email %>
<%= f.input :address %>
<%= f.input :phone %>
<%= f.input :Projects %>
<%= f.radio_button :status, 0, :checked => true%>Publish
<%= f.radio_button :status, 1 %>Unpublish
<%= f.radio_button :status, 2 %>Trash
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
Here i want to put the date picker inside my form as
`<%f.(datepicker)%>`
so that when i submit my form i get the value of date in the parameter date. When i click on date in datepicker it should hide and the default date should point to the current date. my appication.js includes
$(function(){
$('#dp5').datepicker({
format: 'mm-dd-yyyy'
});
$('#dp3').datepicker({
format: 'mm-dd-yyyy'
});
});
Use <%= f.text_field :name_of_the_date_column, :value=>Date.today.strftime('%m-%d-%Y'), :id =>"dp5" %>
To auto hide use this
$("#dt5").datepicker({
format: 'mm-dd-yyyy'
})
.on('changeDate', function(ev){
$('#dt5').datepicker('hide');
});
instead of
$("#dt5").datepicker();
I just answered a similar question here and have included my answer below:
I also needed to get this working and support multiple locales that do not use US centric date formats, eg: en-AU (Australia) which has the date format dd/mm/yyyy.
The Problem
Rails expects the date format to be yyyy-mm-dd from the browser, yet you want to display the date in the user's locale. Whilst the date control allows you to specify the format for display it does NOT allow you to separately specify the format to be sent back to the server.
The Solution
Build a hidden input field that sends the correct format back to your rails server. I do this with with a custom simple_form input control that builds both the date-picker input field and a hidden field, and use some javascript to convert to the rails date when the input control changes.
The upshot is you can have a nice bootstrap date-picker in rails and use it with simple_form as follows:
<%= f.input :date, as: :bootstrap_datepicker %>
Or to use a long date format:
<%= f.input :date, as: :bootstrap_datepicker, input_html: { format: :long } %>
Implementation
Create or edit the following files:
Gemfile
gem 'bootstrap-sass'
gem 'bootstrap-datepicker-rails'
config/locales/en-AU.yml
en-AU:
date:
datepicker:
default: "dd/mm/yyyy"
long: "dd MM, yyyy"
formats:
default: ! '%d/%m/%Y'
long: ! '%d %B, %Y'
config/locales/en-US.yml
en-US:
date:
datepicker:
default: "mm/dd/yyyy"
long: "MM dd, yyyy"
formats:
default: "dd/mm/yyyy"
long: ! '%B %d, %Y'
app/assets/stylesheets/application.css.scss
#import "bootstrap-responsive";
#import "bootstrap-datepicker";
app/assets/javascripts/application.js.coffee
#= require bootstrap
#= require bootstrap-datepicker
#= require bootstrap-datepicker-rails
Alternatively, app/assets/javascripts/application.js
//= require bootstrap
//= require bootstrap-datepicker
//= require bootstrap-datepicker-rails
app/assets/javascripts/bootstrap-datepicker-rails.js.coffee
$ ->
# convert bootstrap-datepicker value to rails date format (yyyy-mm-dd) on our hidden field
$(document).on 'changeDate', '.bootstrap-datepicker', (evt) ->
rails_date = evt.date.getFullYear() + '-' + ('0' + (evt.date.getMonth() + 1)).slice(-2) + '-' + ('0' + evt.date.getDate()).slice(-2)
$(this).next("input[type=hidden]").val(rails_date)
app/inputs/bootstrap_datepicker_input.rb
class BootstrapDatepickerInput < SimpleForm::Inputs::Base
def input
text_field_options = input_html_options.with_indifferent_access
format = text_field_options.delete(:format)
hidden_field_options = text_field_options.dup
hidden_field_options[:class] = text_field_options[:class].dup # so they won't work with same array object
hidden_field_options[:id] = "#{attribute_name}_hidden"
text_field_options[:class] << 'bootstrap-datepicker'
text_field_options[:type] = 'text'
text_field_options[:value] ||= format_date(value(object), format)
set_data_option text_field_options, 'date-format', I18n.t(format, scope: [:date, :datepicker], default: :default)
default_data_option text_field_options, 'provide', 'datepicker'
return_string =
"#{#builder.text_field(attribute_name, text_field_options.to_hash)}\n" +
"#{#builder.hidden_field(attribute_name, hidden_field_options.to_hash)}\n"
return return_string.html_safe
end
protected
def default_data_option(hash, key, value)
set_data_option(hash,key,value) unless data_option(hash, key)
end
def data_option(hash, key)
hash[:data].try(:[],key) || hash["data-#{key}"]
end
def set_data_option(hash, key, value)
hash[:data].try(:[]=,key,value) || (hash["data-#{key}"] = value)
end
def value(object)
object.send #attribute_name if object
end
def format_date(value, format=nil)
value.try(:strftime, I18n.t(format, scope: [ :date, :formats ], default: :default))
end
end
You can express this more concisely:
$("#dt5").datepicker({
format: 'mm-dd-yyyy',
autoclose: true
})
I checked all the answers, none worked for me. I have used the following:
<%= f.text_field :article_date, {"data-provide" => 'datepicker',
"data-date-format" => "yyyy-mm-dd"} %>
In my case, MySQL expected yyyy-mm-dd format, while datepicker default format is mm/dd/yyyy. IMHO, users do not care about format, so I would rather have the same format all over the place and save myself a lot of trouble.
I have a birth_date field that is stored as a datetime value. The default rails form helpers spit out a not-too-friendly format, e.g. "2008-06-10 22:33:19.000000". The below is the vanilla rails way.
<div class="field">
<%= f.label :birth_date %>
<%= f.text_field :birth_date, :size=>"20" %>
</div>
How can I simply apply a format? I tried various approaches, for example strftime should work, I thought. But when I try the following, I get an error undefined method 'strftime' for nil:NilClass
<div class="field">
<%= f.label :birth_date %>
<%= f.text_field :birth_date, :value=>f.object.birth_date.strftime('%m/%d/%Y'), :size=>"20" %>
</div>
Based on some other questions/answers, I tried the following. It works for non-null values, but it is ugly code, and it doesn't work for blank values (actually it shows today's date).
<div class="field">
<%= f.label :birth_date %>
<%= f.text_field :birth_date, :value=> Time.parse(f.object.birth_date.to_s).strftime('%m/%d/%Y'), :size=>"20" %>
</div>
In playing around, it seems that outputting f.object.birth_date is treated as a date, rather than datetime. However, when displayed in the text_field (original, ugly formatting), it includes the time. It is friday afternoon, and my combined lack of familiarity with rails forms and ruby date/time objects is making me feel foolish.
Any simple way to get my form to display nothing if null/blank, and a friendly date otherwise?
If you want a blank string if birth_date is empty, you should simply check that birth_date is non-nil beforehand:
<%= f.text_field :birth_date, :value => (f.object.birth_date.strftime('%m/%d/%Y') if f.object.birth_date), :size => "20" %>
This way, when birth_date is nil, :value gets set to nil.
Have you tried using the date_select form builder helper method? You can also use datetime_select, but it looks like you just want to work with the date here.
<div class="field">
<%= f.label :birth_date %>
<%= f.date_select :birth_date %>
</div>
The API docs are here: http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-date_select
Add on the options you need.
I've always used that approach, or a javascript date selector like this one from jQuery UI. There are plugins for most JS frameworks these days.
If it MUST be a text_field, use a human language date parsing library like chronic. It'll work, but will require that you parse the input from the form somewhere before applying the attribute to your object.