Datepicker chosen date format to Rails backend - ruby-on-rails

I have a Rails 4 app in which we have to present the user with a datepicker but the chosen date displayed should be in MM-DD-YYYY format. When sending the date to Rails, ActiveRecord does not recognize the format as, I know, it is expecting YYYY-MM-DD. Validations fails (date is not present).
The JS is as follows:
$("#some_date").datetimepicker
pickTime: false
format: 'MM-DD-YYYY'
(the display works great with a superb datepicker that appears).
Then my slim template:
= f.input :date, as: :string, label: false, input_html: { class: 'form-control', value: #visit.date.strftime('%m-%d-%Y') }
p.help-block MM-DD-YYYY
If I change the format to YYYY-MM-DD it works perfectly and date is saved into PostgreSQL as is, however in the US, the date is usually displayed as MM-DD-YYYY.
I also don't want to get too involved with helper methods or converting the date from html inputs on each controller so PostgreSQL is happy. I was wondering if there is some way the date format can be changed as it goes to the backend?
Within my config/locales/en.yml, I do have:
date:
formats:
default: '%m/%d/%Y'
Cheers!

Bootstrap datetimepicker doesn't seem to have the option for an alternative format to send to the server. But if all you need is a datepicker and you don't care about time, you can try JQuery datepicker. It allows you to send one dateFormat to display, and an altFormat to send to the server.

In jquery, there is a field called altFormat you can use. The database column doesn’t include time zone information, but the time zone is implicitly UTC. You can use the model method to get the desired format. Instead of saving DB in a specific format I can use model method parse a specific format.
def your_date
self[:column_name].strftime("%m-%D-%Y")
end
and also you want to change time according to user time zone before parsing into the format.
user_record = db_query.your_date
current_user.zone.parse(user_record)
Here are some references might helpful to you.
http://brendankemp.com/essays/dealing-with-time-zones-using-rails-and-postgres/
https://apidock.com/ruby/DateTime/strftime
PS: If you find some other better way plz do post.

Related

Convert jQuery datetimepicker date and time format into a Rails DateTime format

I would need to implement jQuery datetimepicker into my Ruby on Rails 5 application.
There is good documentation for jqueryui Date picker, included two railscasts by Ryan Bates.
As datetimepicker is concerned, I suppose the only concern about rails is to produce a date and time format that rails can easily understand. Once this issue is solved, I think it is easy to add the plugin to the asset pipeline.
Rails DateTime format is "yyyy-mm-dd hh:mm:ss". For instance "2017-07-28 11:24:53".
So I wonder: is there any way to change the default datetimepicker format into a DateTime rails format ?
In the datetimepicker official webpage, the section dedicated to using another date parser/formatter uses as example the MomentJS library. However I could not find examples useful for Rails applications.
jQuery UI Datepicker has a dateFormat option which can be easily used to set the date format to the desired format: how can this be done with datetimepicker?
In your view :
= form_for #event do |f|
= f.text_field :event_start, class: "datepicker"
In your controller
def create
# before the save
#event.event_start = params[:event][:event_start].to_datetime
end

Set and Display Dates in rails via format: %m/%d/%Y

If you want to save a date attribute in a rails form via a text_field: by default rails wants you to put the date in the format of: %Y-%m-%d. ex: '2016-8-25'.
I want to put the date in the format of %m/%d/%Y. ex: '8/25/2016'.
When editing this date attribute: I want it to also display the date in that same format.
I have this specified in my config/locals/en.yml file but it is not working:
en:
date:
formats:
default: "%m/%d/%Y"
If there is another strategy different from above: let me know.
Ultimately: all my date attributes application wide use the bootstrap-datepicker-rails gem. Within forms: this gem wants dates to be in the above format, and it makes sense for dates to be in that format anyways. I do not want to have to override all the writer attributes in order for rails to understand this format.
Update
There appears to be some confusion about my stack overflow question. Users are not actually manually entering dates. They are using a datepicker. And when the user picks a date: it saves the date in a textbox with the format of: mm/dd/yyyy. This is how the clients of this small, in-house app want to display the date (and it makes sense that they want the date displayed this way because they live in the United States and this is a typical date format there).
Ultimately here is the scenario:
Here is the relevant input field in the form:
<div class="field">
<%= f.label :some_date %><br>
<%= f.text_field :some_date, data: {provide: 'datepicker'} %>
</div>
If you manually enter the string: 2016-1-20, and then submit that:
Rails knows how to take that string of 2016-1-20, convert it into a date, and then save that date into the database.
Rails also knows how to redisplay that date within the format of 2016-1-20 if the user wants to go back and edit that date.
I want the exact same setup. The only thing I want to change is the format. Change the format of yyyy-mm-dd to mm/dd/yyyy. So the user would pick a date, and into the input field the value 1/20/2016 would go. That would get submited.
Rails would know how to convert that to a date and save it to the database.
If the user wants to edit this date in the future: it would redisplay in the text field the date in the format of 1/20/2016.
Hopefully this clears up any confusion.
Are you using the l method in your views using this method? It won't work otherwise.
So it looks like this:
<%= l your_date %>
An alternative approach could be creating a file in your config/initializers folder, which can be called date_time.rb for example, and then use this:
Date::DATE_FORMATS[:default] = "%m/%d/%Y"
The best solution I have found is a two-step process:
Allow dates to save within the format of mm/dd/yyyy
Simply add in the american_date gem. And with that: when you enter into a text_field for a date the format of: mm/dd/yyyy (ex: 1/30/2016) it will save the correct date! This works wonderfully with the bootstrap-datepicker-rails gem because when you use the datepicker to pick a date: it loads into the textbox the date in this format.
Display dates in the format of mm/dd/yyyy
however, even with the american_date gem installed: rails still wants to display the date in the yyyy-mm-dd format.
Example: within a text_field, such as: <%= f.text_field :date %>, when the user goes back to edit that date, it will redisplay the date in the format of yyyy-mm-dd which is not what we want. We want rails to redisplay the date in the mm/dd/yyyy format.
Another Example: if you have an erb tag, such as <%= #blog.some_date %> then yet again: rails will display the date in the format of yyyy-mm-dd. Again: this is not what we want. We want that erb tag to automatically redisplay the date in the format of mm/dd/yyyy
To fix this: you have two options:
One option is to open up your config/locals/en.yml file and use the setup specified in the original question of this post. I personally do not like this setup because you then need to remember to use the l method everytime you want to display a date within your app.
The other option (which I like best) is to go to your config/initializers directory and make a new file. Name the file anything you want. I named the file date_display_format.rb. Then within there just put this line: Date::DATE_FORMATS[:default] = "%m/%d/%Y". Now: a date within your erb tags will display in the proper format, and when you go to edit your date attribute within a form: with the text box the date will display in the proper format as well.
For displaying the date in the format you want, you can use the builtin strftime.
For example, if you were displaying the created_at date of an item, you could use the following code to display the saved date in the format of month, day, year. This code would go in a page in your views:
#item.created_at.strftime("%m/%d/%Y")
Or the updated_at date:
#item.updated_at.strftime("%m/%d/%Y")
This would show the created date in the format you want. Then, when you edit it, it will still be displayed in the month, day, year format.

Rails Form Helpers -- Change order of inputs in DATE field

I have <%= f.date_field :day %>, which is asking users to input date in the American format: mm-dd-yyyy.
How can I change it to dd-mm-yyyy ?
While we're at it, how can I change the TIME_FIELD to ask for hours in the 24-hour system (say, instead of inputing 07:00PM, I could say 19:00)?
Thanks in advance
The f.date_field helper will create a standard (native browser) HTML input of type='date'
So you are not able to format the date as such, as per this SO answer.
I recommend you use a jQuery plug in or date picker of some kind.

Working with Times and Dates in Rails

I have a form that is using timepicker addon to select date and time.
My model have a column:
datetime :start_time
When the forms get submitted params hash has:
params[:start_time] #= '08/31/2014 10:50' as a string
What would be a best way to save it in to the database as a datetime format?
I don't fully understand the way how the time is handled, localizations, time zones etc.
When I tried to save it with out formatting, as a string, I am getting argument out of reach error. When I created new Time instance passing params[:start_date] as an argument it was saved as:
0008-01-01 00:01:15 UTC
TY.
You could also try tweaking the timepicker so the client-side will give rails the desired formatting.
This way you only need to config your timepicker once and you won't need to parse the time in the server side every time
Something like:
$(document).ready(function () {
$('#timePicker').datetimepicker({
dateFormat: "dd-mm-yy",
timeFormat: 'hh:mm ss z'
});
});
Check this jsFiddle for a demo
you could write something like this, for getting correct date from your string:
date_time = DateTime.strptime(params[:start_time], '%m/%d/%Y %H:%M')
date_time.to_s #=> "2014-08-31T10:50:00+00:00"

Convert standard rails / ruby time to American format - dates getting mixed up

I'm trying to convert the YYYY-MM-DD format in my forms and show views to MM/DD/YYYY - which is a pretty standard American date format. Not sure how to go about this - I thought that calling .strftime("%m/%d/%Y") on the date instance in /show would do the trick. Very confused - can't find documentation that explains how to convert dates that actually makes sense. I'm following this railscast: http://railscasts.com/episodes/213-calendars-revised
If it helps, I'm using the jQuery datepicker and have this coffeescript:
jQuery ->
$('input.datepicker').datepicker()
dateFormat: 'mm-dd-yy'
weekStart: 0
autoclose: true
_form
<%= f.label :due %><br />
<%= f.text_field :due, { :class => 'datepicker' } %>
The above enters the date with the MM/DD/YYYY format into the form, but it is saved as YYYY-MM-DD
--- UPDATE/SOLUTION FOUND ---
Turns out I was on the right track and not actually crazy. Part of my issue was that I was having a nil object problem which was remedied by calling .try in my views which will only run the method if not nil.
.try(:strftime, "%m/%d/%Y")
Also - I installed the following gem: gem 'american_date' which automagically parses the dates. Works great in show views, but still getting YYYY-MM-DD in form views (edit view only).
We have to solve three tasks when working with dates in RoR. I found these solutions as the most easiest for me:
1.How to display the date correctly.
Install I18n gem and check date format in your config\locales\en.yml. Then use I18n.l() (or just l) form helper to localize dates in your html.erb files.
date:
formats:
default: "%m/%d/%y"
2.How to modify date in convenient way for user.
Use jQuery datepicker (or bootstrap datepicker etc.) and set date format in jQuery widget options in accordance to en.yml format.
3.How to convert date from localized (view) format to activerecord attribute.
Install Delocalize gem and add :input sub-section into date: section of en.yml file.
input:
formats:
- :default
Now your date will be automatically converted from localized format (mm/dd/yy) into database format (yyyy-mm-dd) when you assign it.
I have had to use the altField and altFormat options to get this to work as described:
$('input.datepicker').datepicker({
dateFormat: "mm/dd/yy",
altField: alt_field,
altFormat: "yy-mm-dd"});
This requires having a hidden field alt_field that actually holds your date in the standard db format.
include the below gem, it will automatically save the american date into db format.
gem 'american_date'

Resources