Rails 4 ERB: consistent date format - ruby-on-rails

I have read several posts such as How to format time and date from db:datetime record in Rails 4? and Custom date time format in rails 4 and I feel like I am missing a puzzle piece.
In our project we have setup a conf variable for a date format and we use:
my_date_field.strftime(Rails.configuration.date_format_default)
Other suggestions are to setup an initializer and use:
my_date_field.to_s(format: :date_format_default)
Is there any way to make the output of a datetime field default to a format? In our project, unless we specify, we want a date to ALWAYS render the same way and it feels very un-DRY to have to constantly repeat strftime or to_s, both with their own parameters...

Set a default format in your translations:
en:
time:
formats:
default: "%a %b %d, %Y at %I:%M %p"
Then use the translation helper in your ERb templates:
l some_model.created_at

You can use I18n (Rails Internationalization) to set a default date and time format
config/locales/en.yml
en:
date:
formats:
default: "%d/%m/%Y"
time:
formats:
default: "%d/%m/%Y %H:%M"

Related

How do I convert a non ruby on rails date into a readable format?

Is there anyway in ruby on rails to convert this date 2014-08-13T22:11:18.138Z into a more readable format such as dd/mm/yyyy or jan 1st 2014.
It's from a createdAt field of a parse.com database.
How do I convert this?
Would I need some type of regex?
Is there built in ruby code I can use to do the conversion for me?
You could do with:
// it will be parsed to the datetime in the timezone configured by rails app.
Time.zone.parse('2014-08-13T22:11:18.138Z').strftime('%d/%m/%Y')
The Date class has a whole lot of built in conversions for standard formats. Identify the format ( in this case RFC3339 ) and you will be able to find something like this:
require 'date'
return Date.rfc3339('2014-08-13T22:11:18.138Z')
#<Date: 2014-08-13 ((2456883j,0s,0n),+0s,2299161j)>
In your locale en.yml
date:
formats:
# Use the strftime parameters for formats.
# When no format has been given, it uses default.
# You can provide other formats here if you like!
default: "%d/%m/%Y"
short: "%b %d"
long: "%B %d, %Y"
in your view
<%= I18n.l #entry.created_at, :format => :short %>

YML Date formatting according to user profile settings

Each user of our application can have different format for Date.
I can use something like this Date::DATE_FORMATS[:default] = "%m/%d/%Y" in the application controller for changing by default date formatting.
But i want to change date formats in the en.yml to:
date:
formats:
default: "%Y/%m/%d"
short: "%b %d"
long: "%B %d, %Y"
How can i change default, short and long date formates in yml file on the fly as we can use Date::DATE_FORMATS[:default] = "%m/%d/%Y".
Note: in view i use <%= l Time.now.to_date, :format=>:short%>
Thanks.
You can use in application controller only with different data format.
write in application controller.
Time::DATE_FORMATS.merge!(:data_format => "%d-%B-%Y")
Time::DATE_FORMATS.merge!(:data_format_month => "%m-%d-%Y")
and in view or helper call data_format or data_format_month.
example
created_on.to_s(:data_format) for displaying D-B-Y format
update_on.to_s(:data_format_month ) for displaying M-D-Y format

How to convert date in format 09-feb-73 to 02/09/1973 (mm/dd/yyyy) using Ruby on Rails

How to convert date in format 09-feb-73 to 02/09/1973 (mm/dd/yyyy) using Ruby on Rails?
Valid Ruby datetime formats
Date.strptime("09-feb-73", "%d-%b-%y").strftime("%m/%d/%Y")
Note that strptime is a part of Rails. And these are the relevant formats used:
%b - The abbreviated month name (``Jan'')
%d - Day of the month (01..31)
%m - Month of the year (01..12)
%y - Year without a century (00..99)
%Y - Year with century
You can do it with Date.parse and Date#strftime:
d = Date.parse('09-feb-73').strftime('%m/%d/%Y')
# "02/09/1973"
You could also use Date.strptime instead of Date.parse:
d = Date.strptime('09-feb-73', '%d-%b-%y').strftime('%m/%d/%Y')
# "02/09/1973"
The advantage of strptime is that you can specify the format rather than leaving it to parse to guess.
Date.strptime("09-feb-73", "%d-%b-%y").strftime("%m/%d/%Y")
Date Formats: http://snippets.dzone.com/posts/show/2255
If you require this in a view, I would suggest using localizations, since you can easily change the behavior based on your user's local settings and keep your controller code tidy (why should the controller care about the date format?). Example:
# config/locales/en.yml
en:
time:
formats:
short: "%m/%d/%Y"
# view file
<%=l Time.now, :format => :short %>
For more information on rails localizations, see the Rails Guide.

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.

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