Change date format in the view to dd/mm/yyyy - ruby-on-rails-3

The default date format in Ruby is yyyy-mm-dd, but I needed them to be dd/mm/yyyy in the view
I have wrote a date_format file in config/initializers as:
Time::DATE_FORMATS.merge!( :uk_format => '%m/%d/%Y')
This didn't work since I need to call date.to_s(:uk_format) in order to use this format. But since I'm using <%= f.text_field :paymentDate %> to display the date, I'm not sure I can add to_s to this case.
Can someone help me out please.
Edit 1
Actually date.to_s(:uk_format) doesn't work either, how do I use initializer properly.....?

See: Change default Ruby Time format
Adapted my answer linked to above for the Date and format specified:
Since you're using Rails, take advantage of the I18n support: http://guides.rubyonrails.org/i18n.html#adding-date-time-formats
# config/locales/en.yml
en:
date:
formats:
default: "%d/%m/%Y"
Then you can call I18n.l Date.today to get out a formatted date. Or in your view, you can use <%= l #foo.created_at %>.

Try this instead:
Time::DATE_FORMATS.merge!({:db => '%m/%d/%Y', :uk_format => '%m/%d/%Y'})
Date::DATE_FORMATS.merge!({:db => '%m/%d/%Y', :uk_format => '%m/%d/%Y'})

Related

simple_form date not working after the 12th of each month

Has anyone run into this problem? I have a User object and a simple_form which asks for the User's birthday.
<%= f.input :birthday, as: :date, start_year: Date.today.year - 70,
end_year: Date.today.year, order: [:month, :day, :year], label: false %>
Any date I pick I can only pick a day up to the 12th of each month. If I pick 13th or higher simple_form says "Please enter a valid date". Very strange.
I got this code from https://github.com/plataformatec/simple_form and all it says about this code is "SimpleForm accepts same options as their corresponding input type helper in Rails". Does anyone know where the corresponding input type helper in Rails is documented?
I would guess that you've confused :day and :month somewhere.
Or maybe, put differently, you want to use the American format and instead you're using the european format (or the reverse). Not sure it will help, but see this link:
How can I use US-style dates in Rails using Ruby 1.9?

Rails field "can't be blank", even though it's not blank

I'm using Rails 3 and failing to submit a form because one of the fields fails to pass validates_presence_of. My model is called dinner, and the field, which is used in conjunction with a datepicker, is called date.
views/dinners/new.html.erb:
<%= f.text_field :date, id: "datepicker" %>
models/dinner.rb:
attr_accessible :date
validates_presence_of :date
dinners_controller.rb:
def create
#dinner = Dinner.new params[:dinner]
if #dinner.save
flash[:notice] = "Dinner created successfully."
redirect_to controller: 'dinners'
else
flash.now[:alert] = #dinner.errors.full_messages.join("<br>").html_safe
render action: "new"
end
end
Whenever I fill out all of the fields, including date, I get the error "Date can't be blank", even though it is not blank. What's going on here?
I've found the answer.
My date column was of type date, and before validation Rails ran .to_date on it. Unfortunately, the datepicker that I use creates dates in the American mm/dd/yy format, which Rails can't handle, so .to_date returned nil. That's why the date failed validation: because it really was nil, even though the POST request was fine.
I chose the easy solution and changed the default date of datepicker, as shown here.
Note: For my version of datepicker, I had to use format instead of dateFormat, and also had to use yyyy-mm-dd instead of yy-mm-dd because Rails String#to_date thinks that the year "13" is literally '0013' and not '2013'.

Rails 3 Date format in forms

My question is similar to this SO problem, but it does not answer my question:
Rails 3 default datetime format without UTC
I understand that I can add
Time::DATE_FORMATS[:default] = "%Y/%m/%d"
to my environment.rb and it will change my default time format accordingly.
So when I do Time.now.to_s I get the correct format.
However, my question is, how come this does not work with a form_builder. For example:
<%= f.text_field :date %>
will return a full UTC timestamp: 2013-01-25 07:45:21
I am aware that I can do this
<%= f.text_field :date, :value => #post.date.to_s %>
And it will give me the correct format.
But this solution seems hacky to me. Is this really the only way to do it?
I am not 100% sure. But the answer is most likely no. The rails formhelper just gives you whatever value that is in your database.
Here is where the value is retrieved for your reference:
http://api.rubyonrails.org/classes/ActionView/Helpers/InstanceTag.html#method-i-to_input_field_tag
There is no special processing of it, such as localize or to_s, which is where formatting is applied.
If the date looks like a timestamp (2013-01-25 07:45:21 UTC),
You could do something like the following to views you localize timestamps with:
<%= localize(#post.date, :format => :long) %>
According to your problem, you could try using date_select rather than text_field.
<%= f.date_select :date, :order => [:day, :month, :year] %>

format a date in the rails model

I have a date of birth in the rails model and I display it in different places. Every time I have to specifically format it in mm/dd/yyyy format. Is there something I can do in my model so that every time I get the dob out it comes in mm/dd/yyyy format.
You can define a quick formatted_birthday method in your model, but if you're just outputting this to views you can use Rails' built in date formatting output:
http://guides.rubyonrails.org/i18n.html#adding-date-time-formats
# config/locales/en.yml
en:
time:
formats:
birthday: "%m/%d/%Y"
Then in your view just use:
<%= l person.birthday, :format => 'birthday' %>
Or you can change birthday to default in the format definition and you can omit the :format option all together.
Yes you can. In config/initializers/some_initializer.rb
Date::DATE_FORMATS[:default] = "%m/%d/%Y"
Now all your dates will always be out in the above format.
If you want to selectively choose it only sometimes. Then
Date::DATE_FORMATS[:myformat] = "%m/%d/%Y"
And then you can use whereever you like
your_date.to_s(:myformat)

Searching ActiveRecord by DateTime not working

I asked a question regarding this yesterday, but it was muddled and didn't make sense, so I'm going to boil it down to the core issue.
I have an entries table. When a new record is saved, the entries_controller adds a time to the date column, which is recorded as a datetime. In the new method, I declare a new DateTime as so:
#entry.date = DateTime.new( params[:year].to_i, params[:month].to_i, params[:day].to_i )
I then include it as a hidden field with formtastic:
<%= f.input :date, :as => :hidden %>
Once the entry is saved to the database, the date field looks like 2011-02-10 00:00:00. Everything is working as planned so far, but when I try to retrieve that entry by querying against the date field, I get nil.
I've tried:
search_date = DateTime.new(2011,2,10)
Entry.find_by_date(search_date)
=> nil
I've even tried to search by string, which doesn't make sense since it's a datetime field.
search_time = '2010-02-10 00:00:00'
Entry.find_by_date(search_date)
=> nil
What am I doing wrong here? Why can't I retrieve the record by date?
Would this work for you?
Entry.where("date = #{search_date}")
I just tested this in Rails 3.0.4, mysql2 0.2.6 and
Entry.find_by_date(DateTime.new(2011,2,10))
works.
Having said that, why are you using a datetime column to save a date? Other than it just being a bad idea, you possibly could be running into some kind of timezone issues based on your rails and sql settings. Some automatic timezone conversion could explain the behaviour you are observing but that's just a guess. Please check the development server logs to see if rails is indeed generating the query you wish it to generate.