Transforming Datetime into month, day and year? - ruby-on-rails

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

Related

Date validation in Ruby

How to check if the date is valid date in ruby. Many of the methods are check only the range. But, I need to check the date with day of
week to check whether the date is valid or not. For Ex:
20 Jul 2016 Wed --> Valid
20 Jul 2016 Mon --> Not-Valid
How to do this in ruby ?
I'm not pretend on the best solution ever, but this should work.
def valid_date?(date)
Date.parse(date).strftime("%d %b %Y %a") == date
end
[55] pry(main)> valid_date?("20 Jul 2016 Wed")
=> true
[56] pry(main)> valid_date?("20 Jul 2016 Mon")
=> false
[57] pry(main)>
If you have many formats you may pass format as a second argument
def valid_date?(date, fmt)
Date.parse(date).strftime(fmt) == date
end
=> :valid_date?
[59] pry(main)> valid_date?("20 Jul 2016 Wed", "%d %b %Y %a")
=> true
Hope this will help.
UPDATE
As I mentioned in comment that method name overlaps with existing method valid_date?
So, you may just rename the custom method
def date_valid?(date, fmt)
Date.parse(date).strftime(fmt) == date
end
[2] pry(main)> date_valid?("20 Jul 2016 Wed", "%d %b %Y %a")
=> true
Just out of curiosity:
dates = ['20 Jul 2016 Wed', '20 Jul 2016 Mon']
dates.map do |date|
Date.parse(date).public_send(
Date.instance_methods.detect do |m|
m.to_s =~ /\A#{date[-3..-1].downcase}.*day\?\z/
end)
end
#⇒ [ true, false ]
require 'date'
dates = ['20 Jul 2016 Wed', '20 Jul 2016 Mon']
dates.select do |s|
d = Date.strptime(s[0,11], "%d %b %Y") rescue nil
d.nil? ? false : (Date::ABBR_DAYNAMES[d.wday] == s[-3,3])
end
#=> ["20 Jul 2016 Wed"]
This reads, "select strings 'dd mmm yyyy' that represent valid dates and whose day-of-week matches the day-of-week given by the last three characters of the string".

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.

Translate date(weekday, month) in 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.

How do I format my created_at output correctly with I18n?

I am using this I18n file.
I am calling it in my view like this:
<td class="center"><%= l o.created_at %></td>
This is being outputted like this:
Mon, 22 May 2013 04:04:43 +0000
For starters, why is it displaying May 22, 2013 and not April 22?
When I do it in the console, I get this:
> o.created_at
=> Mon, 22 Apr 2013 04:04:43 UTC +00:00
I don't want it to display the time, or rather would prefer to just say something like:
Monday, April 22, 2013 # 4:04am
How do I do that?
You can add custom date/time formats to your translation file. To see what time-based substitutions are possible, consult a reference for strfime
formats:
default: ! '%Y-%m-%d'
long: ! '%B %d, %Y'
short: ! '%b %d'
custom: ! '%A, %M %B, %Y # %l:%M%P'
In your view, you'd make use as follows:
<%= l o.created_at, :format => :custom %>
You may need to get rid of blank entries in your en.yml file to correct your translation errors.

Ruby String to Date Conversion

I am faced with an issue in Ruby on Rails. I am looking to convert a string of format Tue, 10 Aug 2010 01:20:19 -0400 (EDT) to a date object.
Is there anyway i could do this.
Here is what I've looked and tried at the following with no luck:
Date.strptime(updated,"%a, %d %m %Y %H:%M:%S %Z")
Chronic Parser
Ruby: convert string to date
Parsing date from text using Ruby
Please help me out with this.
What is wrong with Date.parse method?
str = "Tue, 10 Aug 2010 01:20:19 -0400 (EDT)"
date = Date.parse str
=> #<Date: 4910837/2,0,2299161>
puts date
2010-08-10
It seems to work.
The only problem here is time zone. If you want date in UTC time zone, then it is better to use Time object, suppose we have string:
str = "Tue, 10 Aug 2010 01:20:19 +0400"
puts Date.parse str
2010-08-10
puts Date.parse(Time.parse(str).utc.to_s)
2010-08-09
I couldn't find simpler method to convert Time to Date.
Date.strptime(updated,"%a, %d %m %Y %H:%M:%S %Z")
Should be:
Date.strptime(updated, '%a, %d %b %Y %H:%M:%S %Z')
str = "Tue, 10 Aug 2010 01:20:19 -0400 (EDT)"
str.to_date
=> Tue, 10 Aug 2010
You can try https://rubygems.org/gems/dates_from_string:
Find date in structure:
text = "get car from repair 2015-02-02 23:00:10"
dates_from_string = DatesFromString.new
dates_from_string.find_date(text)
=> ["2015-02-02 23:00:10"]

Resources