Human Readable Date in Rails - ruby-on-rails

I am trying to have the current date displayed in a view within my rails app. I'd like the following format: Day of week, Month, Day, Year.
Currently I am using:
<%= Time.now.strftime("%B %d, %Y") %>
This displays everything but the day of the week. How do I add the day of the week?

%A gives the day of the week
Customize how you prefer it!
<%= Time.now.strftime("%B %d, %Y, %A") %>

You can get the the name of the day as follows:
Time.now.strftime("%B %d, %Y %a") # => "January 18, 2014 Sat"
Time.now.strftime("%B %d, %Y %A") # => "January 18, 2014 Saturday"
You can also get day names from numbers 0...7 using Date::DAYNAMES like this:
require 'date'
(0...7).each { |x| puts Date::DAYNAMES[x] }
# Sunday
# Monday
# Tuesday
# Wednesday
# Thursday
# Friday
# Saturday
# => 0...7

You can use %A to display the full name e.g. Monday or %a for an abbreviated name e.g. Mon:
Time.now.strftime("%A, %B %d %Y") # => "Sunday, January 19, 2014"
Time.now.strftime("%a, %B %d %Y") # => "Sun, January 19, 2014"
Refer to the docs for more info.

You can use the followings:
distance_of_time_in_words(from_time, to_time) or
time_ago_in_words(from_time)
For example:
<span class="posted">Posted on <%= time_ago_in_words(post.created_at) %> ago</span>

Related

Formatting Date in Rails

How can I format this datetime attribute 2017-10-15 or how can I get the 15th of the current month?
#today = Time.now
#mid = time.strftime("%Y-%m-15")
into October 15, 2017? I tried using to_formatted_s(:long), but it gives an error of undefined method.
In Rails 4 or above
> Date.today.beginning_of_month + 14
#=> Sun, 15 Oct 2017
# formatted as per your requirement
> (Date.today.beginning_of_month + 14).strftime("%B %d, %Y")
#=> "October 15, 2017"
Date#beginning_of_month it will return you beginning date of month of specified date (which will be always 1st, add 14 days) so you will get 15th of that month
Mydate = "2017-10-15"
Mydate.to_date.strftime("%B %d, %Y")
=> "October 15, 2017"
Using #GaganGami solution, you can create a Date class method middle_of_current_month
class Date
def self.middle_of_current_month
(today.beginning_of_month + 14).strftime("%B %d, %Y")
end
end
Date.middle_of_current_month
#=> "October 15, 2017"

Format unix timestamp to something readable

I'm trying to parse some bits through the google analytics cookie parser, I have this:
:Time_of_first_visit__c => Time.new(#data.utma_hash.fetch(:initial_visit_at)).to_datetime.to_formatted_s(:long),
:Time_of_previous_visit__c => Time.new(#data.utma_hash.fetch(:previous_visit_at)).to_datetime.to_formatted_s(:long),
:Current_visit_time__c => Time.new(#data.utma_hash.fetch(:current_visit_at)).to_datetime.to_formatted_s(:long),
But it's rendered like this:
Time of first visit
January 01, 1375174064 00:00
Current visit time
January 01, 1375174064 00:00
Time of previous visit
January 01, 1375174064 00:00
try to remove to_formatted_s(:long) and use it as argument of I18n.l
example:
I18n.l Time.new(#data.utma_hash.fetch(:initial_visit_at)).to_datetime
Of course you need a specification of datetime formats in your language .yml file, but it should work with the default one you can find in the official guides
This was the code I went with in the end:
:Time_of_first_visit__c => Time.at(#data.utma_hash.fetch(:initial_visit_at).to_i + 1.hour).strftime("%B %e, %Y at %I:%M %p"),
:Time_of_previous_visit__c => Time.at(#data.utma_hash.fetch(:previous_visit_at).to_i + 1.hour).strftime("%B %e, %Y at %I:%M %p"),
:Current_visit_time__c => Time.at(#data.utma_hash.fetch(:current_visit_at).to_i + 1.hour).strftime("%B %e, %Y at %I:%M %p"),

How to handle a `datetime` value so to change it from `2012-04-27 00:00:00` to `27 april 2012`?

I am using Ruby on Rails v3.2.2 and I would like to display a data as-like <day_number> <month_name> <year_number>. That is, I have a datetime database table column and I would like to change its contained values, for example, from 2012-04-27 00:00:00 to 27 april 2012.
How can I make that?
The standard way is use rails localization.
model
I18n.l(datetime, :format => :short)
controller
I18n.l(datetime, :format => :long)
view
<%= l(datetime), :format => :custom %>
config/locales/en.yml
en:
time:
formats:
long: "%A %B %d %Y | %I:%M %p GMT"
short: "%d %B %Y, %H:%M GMT"
custom: "your custom format"
date:
formats:
short: "%d %B %Y"
long: "%A %B %d %Y"
custom: "your custom format"
In your case the format should be "%d %A %Y".
The benefit is if you want to change format you can do it in one place for all datetimes which you are using.
You can use the method
str_name.strftime("%d %A %Y")

Extra space in cucumber step when using to_s(:long)

I have a step that fails with the following...
expected #has_content?("July 4, 2009") to return true, got false
The problem, I think, is the extra space between "July" and "4". I am using published_on.to_s(:long) in both the step definition and the view, so I'm not entirely sure where the extra space is coming from.
Any ideas?
It's what happens when you try:
Date.civil(2010, 7, 4).strftime("%e") # => " 4"
And Rails uses %e in their :long format. The funny thing is that %e isn't documented.
I would adjust my step definition to match Ruby behavior if you don't care about the extra space (extra spaces won't show in HTML anyway). If you do care about it, squish it:
Date.civil(2010, 7, 4).to_s(:long).squish # => "July 4, 2010"
Squish is avaiable in Rails 3. If you're using Rails 2, you can use gsub:
Date.civil(2010, 7, 4).to_s(:long).gsub(/\s+/, " ") # => "July 4, 2010"
I ran into the same problem with my cucumber test today!
The problem (as iain pointed out) is that Date::DATE_FORMATS[:long] is "%B %e, %Y". The %e, according to ri strftime, yields a blank-padded day number:
%d - Day of the month, zero-padded (01..31)
%-d no-padded (1..31)
%e - Day of the month, blank-padded ( 1..31)
So by default, this is what I see in Rails 3.1.3:
> d = '2012-02-01'.to_date
=> Wed, 01 Feb 2012
> d.to_s(:long)
=> "February 1, 2012"
Strangely, Rails uses a different day format for the :long format of times (%d, which yields "01") as for dates (%e, which yields " 1"):
> d = '2012-02-01'.to_time
=> 2012-02-01 00:00:00 UTC
> d.to_s(:long)
=> "February 01, 2012 00:00"
> Time::DATE_FORMATS[:long]
=> "%B %d, %Y %H:%M"
> Date::DATE_FORMATS[:long]
=> "%B %e, %Y"
The solution then is to use "%-d" for the day in your format string instead of %e:
> Date::DATE_FORMATS[:long] = "%B %-d, %Y"
=> "%B %-d, %Y"
> d = '2012-02-01'.to_date
Wed, 01 Feb 2012
> d.to_s(:long)
=> "February 1, 2012"
You can just add this line to a new initializer, config/initializers/date_formats.rb:
Date::DATE_FORMATS[:long] = "%B %-d, %Y"
Please comment on https://github.com/rails/rails/pull/1994 if you would like to see this default changed in Rails.
For what it's worth, I would rather use the "%-d" fix (or even "%-e"! which gives the same results) than ".squish", which is Rails-specific, and not as portable (why not use the Ruby-native ".squeeze", or even ".squeeze(' ')" at that then, if you don't want to mess around with the date formats?).
Also, as an update: #iain mentions that '%e' isn't documented. For what it's worth, it is now! (although interestingly, not "%-e" specifically, which, if you do try it, is valid, and works!)

Transforming Datetime into month, day and year?

I can't seem to find this and I feel like it should be easy. In Ruby on Rails, how do I take:
2010-06-14 19:01:00 UTC
and turn it into
June 14th, 2010
Can I not just use a helper in the view?
I don't know for
June 14th, 2010
But if you want
June 14, 2010
Ref how do i get name of the month in ruby on Rails? or this
Just do
#date = Time.now
#date.strftime("%B %d, %Y")
And for suffix use following
#date.strftime("%B #{#date.day.ordinalize}, %Y") # >>> Gives `June 18th, 2010`
Time and date formats in rails:
Date
====
db:‘%Y-%m-%d’ 2008-08-20
long_ordinal:‘&proc’ August 20th, 2008
long:‘%B %e, %Y’ August 20, 2008
rfc822:‘%e %b %Y’ 20 Aug 2008
number:‘%Y%m%d’ 20080820
short:‘%e %b’ 20 Aug
DateTime
====
db:‘%Y-%m-%d’ 2008-08-20 16:56:21
long_ordinal:‘&proc’ August 20th, 2008 16:56
long:‘%B %e, %Y’ August 20, 2008 16:56
rfc822:‘%e %b %Y’ Wed, 20 Aug 2008 16:56:21 -0600
number:‘%Y%m%d’ 20080820165621
short:‘%e %b’ 20 Aug 16:56
Time
====
db:‘%Y-%m-%d %H:%M:%S’ 2008-08-20 16:56:21
long_ordinal:‘&proc’ August 20th, 2008 16:56
long:‘%B %d, %Y %H:%M’ August 20, 2008 16:56
rfc822:‘%a, %d %b %Y %H:%M:%S %z’ Wed, 20 Aug 2008 16:56:21 -0600
short:‘%d %b %H:%M’ 20 Aug 16:56
number:‘%Y%m%d%H%M%S’ 20080820165621
time:‘%H:%M’ 16:56
for example:
<%= news.created_at.strftime("%B %d, %Y %H:%M") %>
Thanks http://onrails.org/2008/08/20/what-are-all-the-rails-date-formats.html
For future reference: Rails date time formats
You don't need to save it in a variable.
Time.now.strftime("%Y-%m-%d") # 2013-01-08
Needs the Time module for Time.parse and ActiveSupport for Integer#ordinalize:
require 'time'
require 'active_support'
input = '2010-06-14 19:01:00 UTC'
t = Time.parse(input)
date = "%s %s, %d" % [t.strftime("%B"), t.day.ordinalize, t.year]
# => "June 14th, 2010"
Just the other day there was a similar question. In my answer how do I get name of the month in ruby on Rails? I showed how you can add a custom to_s definition in your config/environment.rb file.
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
:my_own_long_date_format => "%B %d, %Y")
Now you can call Time.now.to_s(:my_own_long_date_format) from any view to get:
June 15, 2010
Update that is working in Rails 5 :
<%= l #user.created_at, format: :short %>
Internationalize :
<%= I18n.l( #user.created_at, format: :short) %>
You can use :long instead of :short

Resources