Translate date(weekday, month) in Rails - ruby-on-rails

Now when I add something to my database it enter created_at parameter also. When I use it in my view, it looks like this:
Thursday, 11 Jun 2015 9:52 AM
And I use it as:
<%= #current_feed.created_at.strftime("%A, %d %b %Y %l:%M %p") %>
Can I translate month and weekdays? Or create dictionary for it?

Try this .......
date = Date.parse('Thursday, 11 Jun 2015 9:52 AM')
=> Thu, 11 Jun 2015
date.mon
=> 6
date.mday
=> 11
date.wday
=> 4
Hope this will work for you.

I guess you are asking about date translation. Have a look at this question.
You should use I18n.localize. Refer this document.
You can also have a look at this question, to know how to have months in locale.

Related

Convert Active Support timezone original format into a string

I'm trying to convert Active Support timezone original format into a string. I want to store it in an array of characters then parse each needed data individually.
Time.zone = current_user.timezone
date_and_time = Time.zone.now
Now
date_and_time = Thu, 21 Apr 2016 20:58:04 PDT -07:00
Ruby method ( to_s ) does not convert it. I found other ways to convert it to but all of them will change the format to numbers only, I want the day to stay the same because I will store it in a variable then use it in a different method.
You can use .to_formatted_s(DATE_FORMAT) for this.
time = Time.now # => Thu Jan 18 06:10:17 CST 2007
time.to_formatted_s(:db) # => "2007-01-18 06:10:17"
time.to_formatted_s(:long) # => "January 18, 2007 06:10"
time.to_formatted_s(:long_ordinal) # => "January 18th, 2007 06:10"
time.to_formatted_s(:rfc822) # => "Thu, 18 Jan 2007 06:10:17 -0600"
time.to_formatted_s(:iso8601) # => "2007-01-18T06:10:17-06:00"
A list of all DATE_FORMATS and more information can be found here:
http://api.rubyonrails.org/classes/Time.html#method-i-to_formatted_s
You can try this
date_and_time.strftime("%a %d %b %Y")
Also You can check this guide, to get format you want
You should get what you want using this :
date_and_time.strftime("%a %d %b %Y %H:%M:%S UTC %:z")
Please see strftime Docs for more info
Explanation
Reason for hardcoding UTC is so that according to the docs
%z - Time zone as hour and minute offset from UTC
So i believe it should be UTC all the time.

Select object based on date range

Tech specs: ruby 2.1.5p273, Rails 4.2.3.
I have an array of Days that I want to loop through to pick the right Exits (model) that fall within a date range.
#exits has :start_date and :end_date
#days is an array of dates like:
=> [Sun, 06 Sep 2015, Sat, 12 Sep 2015, Tue, 15 Sep 2015, Fri, 18 Sep 2015, Sat, 19 Sep 2015, Sun, 20 Sep 2015, Wed, 23 Sep 2015]
I thought something like this would work:
#days.each do |day|
#exits.where(:start_date..:end_date).include?(day)
end
but I get an error:
TypeError: Cannot visit Range
What is the best way to query an object that has a date range (between two fields) by comparing it against a single date? Thanks!
You can use the following:
#days.each do |day|
exits = Exit.where('? BETWEEN start_date AND end_date', day)
# etc.
end
If you don't want to loop over them then you can do:
Event.where("start_date IN (:days) AND end_date IN (:days)", { days: #days })
or
Event.where(start_date: #days, end_date: #days)
Exit.where(day: #exit.start_date..#exits.end_date)
or
Exit.where('day >= ? AND day <= ?', #exit.start_date, #exits.end_date)
Doing SQL queries in a loop is probably a bad idea, it could be refactored to be be one call most likely. And this should happen in the controller not in the view.

Rails DateTime.now without Time

I need to use DateTime.now to grab the current date, and "strip off" the time.
For example, this shows what I don't want: DateTime.now => Sat, 19 Nov 2011 18:54:13 UTC +00:00
This shows what I do want: DateTime.now.some_operation => 2011-11-06 00:00:00 UTC
You can use one of the following:
DateTime.current.midnight
DateTime.current.beginning_of_day
DateTime.current.to_date
What you need is the function strftime:
Time.now.strftime("%Y-%d-%m %H:%M:%S %Z")
You can use just:
Date.current
What about Date.today.to_time?
If you're happy to require 'active_support/core_ext', then you can use
DateTime.now.midnight # => Sat, 19 Nov 2011 00:00:00 -0800
If you want today's date without the time, just use Date.today
Figured it out. This works:
DateTime.now.in_time_zone.midnight

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

In Ruby on Rails, how do I format a date with the "th" suffix, as in, "Sun Oct 5th"?

I want to display dates in the format: short day of week, short month, day of month without leading zero but including "th", "st", "nd", or "rd" suffix.
For example, the day this question was asked would display "Thu Oct 2nd".
I'm using Ruby 1.8.7, and Time.strftime just doesn't seem to do this. I'd prefer a standard library if one exists.
Use the ordinalize method from 'active_support'.
>> time = Time.new
=> Fri Oct 03 01:24:48 +0100 2008
>> time.strftime("%a %b #{time.day.ordinalize}")
=> "Fri Oct 3rd"
Note, if you are using IRB with Ruby 2.0, you must first run:
require 'active_support/core_ext/integer/inflections'
You can use active_support's ordinalize helper method on numbers.
>> 3.ordinalize
=> "3rd"
>> 2.ordinalize
=> "2nd"
>> 1.ordinalize
=> "1st"
Taking Patrick McKenzie's answer just a bit further, you could create a new file in your config/initializers directory called date_format.rb (or whatever you want) and put this in it:
Time::DATE_FORMATS.merge!(
my_date: lambda { |time| time.strftime("%a, %b #{time.day.ordinalize}") }
)
Then in your view code you can format any date simply by assigning it your new date format:
My Date: <%= h some_date.to_s(:my_date) %>
It's simple, it works, and is easy to build on. Just add more format lines in the date_format.rb file for each of your different date formats. Here is a more fleshed out example.
Time::DATE_FORMATS.merge!(
datetime_military: '%Y-%m-%d %H:%M',
datetime: '%Y-%m-%d %I:%M%P',
time: '%I:%M%P',
time_military: '%H:%M%P',
datetime_short: '%m/%d %I:%M',
due_date: lambda { |time| time.strftime("%a, %b #{time.day.ordinalize}") }
)
>> require 'activesupport'
=> []
>> t = Time.now
=> Thu Oct 02 17:28:37 -0700 2008
>> formatted = "#{t.strftime("%a %b")} #{t.day.ordinalize}"
=> "Thu Oct 2nd"
Although Jonathan Tran did say he was looking for the abbreviated day of the week first followed by the abbreviated month, I think it might be useful for people who end up here to know that Rails has out-of-the-box support for the more commonly usable long month, ordinalized day integer, followed by the year, as in June 1st, 2018.
It can be easily achieved with:
Time.current.to_date.to_s(:long_ordinal)
=> "January 26th, 2019"
Or:
Date.current.to_s(:long_ordinal)
=> "January 26th, 2019"
You can stick to a time instance if you wish as well:
Time.current.to_s(:long_ordinal)
=> "January 26th, 2019 04:21"
You can find more formats and context on how to create a custom one in the Rails API docs.
Create your own %o format.
Initializer
config/initializers/srtftime.rb
module StrftimeOrdinal
def self.included( base )
base.class_eval do
alias_method :old_strftime, :strftime
def strftime( format )
old_strftime format.gsub( "%o", day.ordinalize )
end
end
end
end
[ Time, Date, DateTime ].each{ |c| c.send :include, StrftimeOrdinal }
Usage
Time.new( 2018, 10, 2 ).strftime( "%a %b %o" )
=> "Tue Oct 2nd"
You can use this with Date and DateTime as well:
DateTime.new( 2018, 10, 2 ).strftime( "%a %b %o" )
=> "Tue Oct 2nd"
Date.new( 2018, 10, 2 ).strftime( "%a %b %o" )
=> "Tue Oct 2nd"
I like Bartosz's answer, but hey, since this is Rails we're talking about, let's take it one step up in devious. (Edit: Although I was going to just monkeypatch the following method, turns out there is a cleaner way.)
DateTime instances have a to_formatted_s method supplied by ActiveSupport, which takes a single symbol as a parameter and, if that symbol is recognized as a valid predefined format, returns a String with the appropriate formatting.
Those symbols are defined by Time::DATE_FORMATS, which is a hash of symbols to either strings for the standard formatting function... or procs. Bwahaha.
d = DateTime.now #Examples were executed on October 3rd 2008
Time::DATE_FORMATS[:weekday_month_ordinal] =
lambda { |time| time.strftime("%a %b #{time.day.ordinalize}") }
d.to_formatted_s :weekday_month_ordinal #Fri Oct 3rd
But hey, if you can't resist the opportunity to monkeypatch, you could always give that a cleaner interface:
class DateTime
Time::DATE_FORMATS[:weekday_month_ordinal] =
lambda { |time| time.strftime("%a %b #{time.day.ordinalize}") }
def to_my_special_s
to_formatted_s :weekday_month_ordinal
end
end
DateTime.now.to_my_special_s #Fri Oct 3rd

Resources