Rails date format in form field - ruby-on-rails

I'd like my dates in the mm/dd/year format in text fields. However, they currently displays as 2010-03-26.
Is there a global setting I can set to change this?
I tried the following, which seems to update the .to_s method, but form fields stay the same.
ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(:default => '%m/%d/%Y')
Thanks

You have to register the default format in an initializer.
Add this line to the config/initializers/date_time_formats.rb.
Date::DATE_FORMATS[:default] = '%m/%d/%Y'
# if you want to change the format of Time display then add the line below
Time::DATE_FORMATS[:default]= '%m/%d/%Y %H:%M:%S'
# if you want to change the DB date format.
Time::DATE_FORMATS[:db]= '%m/%d/%Y %H:%M:%S'
Now in the script\console lets test the format.
>> Date.today.to_s
=> "03/14/2010"
>> Time.now.to_s
=> "03/14/2010 13:20:55"

I don't know if there is a global setting for that anywhere, I just do it in the ERB.
<%= text_field_tag("air_date_date", air_date.blank? ? "" : air_date.strftime("%m/%d/%Y"), :class => "date-input text") %>
Alternatively, you can factor this out into a helper function to make it DRY.

I know this is an awfully old question, but you could use date_field instead of text_field. Perhaps that wasn't an option when you asked this question originally.
It displays the date in mm/dd/yyyy, which is your intent.
<%= date_field :column_name %>

The date_select form helper provides a "bare bones" date selector.

Related

Change default Ruby Time format

I keep having to append ".strftime("%H:%M")" to anything that is displaying a time in my Rails project. I have a start time and an end time for each Concert object, so I have to append ".strftime("%H:%M")" whenever I wanna display those times.
Note that I'm not asking to change the date format. The date looks fine as it is (as MM/DD/YYYY).
What's the best way to get around this? Is there a way to set the default time format?
(I'm pretty sure this is only a Ruby thing, but I'm a newbie, so I'm not sure.)
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:
time:
formats:
default: "%H:%M"
Then when you call I18n.l Time.now or <%= l Time.now %>, it'll use that format automatically.
Ruby on Rails has built-in presets for formatting Date and Time instances. Here's what they are for Time on my machine:
>> Time::DATE_FORMATS
=> {:short=>"%d %b %H:%M", :db=>"%Y-%m-%d %H:%M:%S", :rfc822=>#<Proc:0x0000000103700b08#/Users/donovan/.gem/gems/activesupport-3.0.1/lib/active_support/core_ext/time/conversions.rb:13>, :time=>"%H:%M", :number=>"%Y%m%d%H%M%S", :long_ordinal=>#<Proc:0x0000000103700e50#/Users/donovan/.gem/gems/activesupport-3.0.1/lib/active_support/core_ext/time/conversions.rb:12>, :long=>"%B %d, %Y %H:%M"}
You can easily use them like so:
>> Time.now.to_s(:db)
=> "2011-01-12 15:26:11"
You can define your own and use it, too:
>> Time::DATE_FORMATS[:mine] = "%H:%M"
=> "%H:%M"
>> Time.now.to_s(:mine)
=> "15:28"
You could create a custom function in your application_helper.rb file. Maybe something like:
def custom_time(date)
date.strftime("%H:%M")
end
Not sure if this is best practice but it should work well.
I use an initializer: config/initializers/time_formats.rb which contains:
[Time, Date].map do |klass|
klass::DATE_FORMATS[:app_date] = "%m/%d/%Y"
klass::DATE_FORMATS[:app_month_and_year] = "%B %Y"
klass::DATE_FORMATS[:app_abbrev_month_and_year] = "%b %Y"
...
end
Then I use Time.now.to_s(:app_date), etc based on how I want to display it.
You could add Time::DATE_FORMATS[:default] = "%H:%M" to accomplish what you're trying to do. This is not internationalized though - for that, coreyward's answer is probably better.

Rails 3 default datetime format without UTC

I'm creating a new Rails 3 app, and in it I use DateTime for a couple of fields, however every datetime field standard has UTC behind it (in a view), like:
2010-10-10 16:19:00 UTC
How do I get rid of the UTC part?
UPDATE: here's what I have so far:
<%= trip.truckleft.strftime("%Y-%m-%d %H:%M") %>
So all I have to do now is put that in a helper, but isn't there a better more universal way?
I looked at some other posts, that suggested creating a time_formats.rb in initializers, however I didn't have any success doing that.
Thanks for your help, much appreciated!
Another -- perhaps now preferred -- way is to use Rails' internationalization and localization support. There's a lot to learn in that guide, so the tl;dr version is this:
<%= l trip.truckleft, :format => :long %>
There are a few predefined date and time formats like :long available to you already for English, and you can add your own in config/locales/en.yml by following the YAML structure in those examples. If you're not getting heavily into the whole i18n/l10n thing just yet and looking at the l method all the time is confusing, you can also use:
<%= trip.truckleft.to_formatted_s(:long) %>
Here is what finally worked for me:
I created a new file in:
config/initializers/
named: time_formats.rb
and added this to that file:
Time::DATE_FORMATS[:default] = "%Y-%m-%d %H:%M"
Then I saved, restarted the server and it started to work.
I'm using i18n to format my dates and have this in en.yml:
date:
formats:
default: "%m/%d/%Y"
I wanted to reuse that format for how the models show their dates, so my config/initializers/time_formats.rb contains this:
Date::DATE_FORMATS[:default] = lambda { |date| I18n.l(date) }
To be exact, you should put these in your initializers:
Date::DATE_FORMATS[:default] = "%m-%d-%Y"
Time::DATE_FORMATS[:default] = "%m-%d-%Y %H:%M"
When having datetime, the second one will work (for example: created_at for in models).
You can put the following line at the end of your config/environment.rb file:
Date::DATE_FORMATS[:default] = "%Y-%m-%d %H:%M"
for rails 3
add to config/environment.rb
my_datetime_formats = { :default => '%F %T' } #or any other you like
my_date_formats = { :default => '%F' } #or any other you like
Time::DATE_FORMATS.merge!(my_datetime_formats)
Date::DATE_FORMATS.merge!(my_date_formats)
(the difference from other answers - is merge! method)

Ruby on Rails: formatting date inside a field

My field:
<%= f.text_field :expires_at, :label => false, :class => "input-field" %>
but I want the date to be kinda like this when the page loads: June, 1st, 1752 9:54:00 pm
How would I do that?
Why are you using a text_field for a datetime? Consider using time_select instead.
If you really want to format a date that way though, just use strftime.
So, in your case, add
:value => #object.expires_at.strftime('%B %d, %Y %H:%M:%S %p')
You can format dates and times using the strftime method.
See Ruby's strftime and then use :value => #date_value
If you want this date format to be used throughout your application, you can set the default format in your environment.rb file:
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(:default => "%a %m/%d/%Y %I:%M%p")
If you do this, every time you display a date, it will be formatted according to the date format string you've provided.

Validating date formats in rails

My simple date validation regex is not working correctly...
validates_format_of :dob, :with => /\d{2}\/\d{2}\/\d{4}/, :message => "^Date must be in the following format: mm/dd/yyyy"
What am I missing here? I'm trying to validate that a date is in the following format: mm/dd/yyyy - When I enter what should be valid data, I still get the error message.
Thanks for the help so far. Here's a snippet of code from my form that is passing the dob value in:
<tr>
<td>
<%= f.label :dob, "Date of Birth: " %>
</td>
<td>
<%= calendar_date_select_tag "user[dob]", "", :format => :american, :year_range => 50.years.ago..0.years.ago %>
</td>
</tr>
I think it may have something to do with my use of this js calendar plugin. A related problem is that my dob value is not maintained in the field if the post fails validation - the previously entered date value clears out...
Thanks!
Tom
You are probably using a string field to store a date. Consequently, any helpers that expect a DateTime or Time value will not work properly. You will need to investigate multiparameter assignments in Rails to figure out the proper way to do what you want to do (multiparemeter assignments is the magic behind sending 4 fields to Rails and get them converted to a DateTime or Time object).
In other words: if you are using a true DateTime field (as you should for this case) the validates_format_of will not have any effect (or will have adverse effects)
Found an excellent gem / plugin for all your date / time validations.
validates_timeliness
http://github.com/adzap/validates_timeliness
I've not tested your code within a Rails app, but your regular expression looks good to me. Try this test program:
#!/usr/bin/ruby
str = '08/24/2009'
regex = /\d{2}\/\d{2}\/\d{4}/
if str =~ regex
print 'matched', "\n"
else
print 'did not match', "\n"
end
Your regular expression matches. That suggests the problem is elsewhere.
You also might think about trying more general solutions for parsing a date in Ruby, such as the Date.parse method of the Date class. This does a little bit more validation than your regular expression, and it also provides some useful methods for converting dates between different formats.
Ahhh! Forcing date formats on the end-user when Rails implicitly converts them is a bad thing for usability, along with being more work for you (as you've seen).
If you've got a date/time attribute in your model, Rails will do its best to convert via Date.Parse (http://www.ruby-doc.org/core/classes/Date.html#M000644), e.g.
u = Somemodel.find :first
u.created_at
=> Tue Nov 20 15:44:18 -0500 2007
u.created_at = '2008/07/03'
=> "2008/07/03"
u.created_at
=> Thu Jul 03 00:00:00 -0400 2008
u.created_at = '05/10/1980'
=> "05/10/1980"
u.created_at
=> Sat May 10 00:00:00 -0400 1980
The regex looks correct to me. A useful resource is http://www.rubyxp.com/, which will test your regular expression against a given string. Indeed, the regex you have matches a date I typed into rubyxp.
Perhaps there's an issue in getting the entered data -- any chance the field is really called da?
Another item you may find useful: validates_timeliness, a rails plugin to validate dates and times. Why just validate the date format when you can check if it's a real date -- after all, 99/99/9999 will validate against your regex, but you may not really want to accept that.
You can try using current date to convert it into a format something like his:
def validate_date_format(value)
current_date = DateTime.now
begin
DateTime.strptime(current_date, value)
rescue
raise 'Invalid Format'
end
end
You might also want to look into the Chronic Gem (http://chronic.rubyforge.org/) which does natural date parsing. So you can enter in :
Next tuesday at 9pm
And it will interpret it correctly.

Formatting timestamps

How do you format Rails timestamps in a more human-readable format? If I simply print out created_at or updated_at in my view like this:
<% #created = scenario.created_at %>
Then I will get:
2009-03-27 23:53:38 UTC
The strftime (from Ruby's Time) and to_formatted_s (from Rails' ActiveSupport) functions should be able to handle all of your time-formatting needs.
Take a look at the I18n functionality. It allows you to do the following in your views:
<%= localize(scenario.created_at, :format => :long) %>
where the formats are defined in your locales.
More info
Also
<%= l scenario.created_at, :format => :sample) %>
And in locales/en.yml(depending of language)
en:
time:
formats:
sample: '%d.%m.%Y'
To learn more, see - http://guides.rubyonrails.org/i18n.html
Time.now().to_i works great. For reverse conversion use Time.at(argument)
You can use strftime to format the timestamp in many ways. I prefer some_data[:created_at].strftime('%F %T'). %F shows "2017-02-08" (Calendar date extended), and %T shows "08:37:48" (Local time extended).
For timezone issues, add this lines to your config/application.rb file
config.time_zone = 'your_timezone_string'
config.active_record.default_timezone = :local
See below for 1.Make a timestamp and 2.Format a timestamp
1.Make a timestamp
This line code in Ruby Time.now.getutc returns a UTC time stamp e.g. 2022-07-05 15:20:40.976321 UTC.
2.Format a timestamp
You can then format it with strftime. The 2 lines of code:
timestamp_UTC=Time.now.getutc
timestamp_UTC_formated=timestamp_UTC.strftime("%Y%m%d_%Hh%Mm%Ss")
return a timestamp formated, e.g. "20220705_15h23m24s".
See strftime documentation for the formatting syntax.
you have to modify the timestamp file, in my case this file is located in /usr/local/rvm/gems/ruby-2.0.0-p195/gems/activerecord-4.2.0/lib/active_record/timestamp.rb. You must search for this line:
self.class.default_timezone == :utc ? Time.now.utc : Time.now
and change it to this:
self.class.default_timezone == :utc ? Time.now.utc : Time.now.strftime('%Y-%m-%d %H-%M-%S')
The trick is to modify the format with the strftime method, you can change the format if you want.
Now rails will use your format to update the "updated_at" column.

Resources