开发者

Ruby/Rails - Convert Date/Time back into Natural Language (2011-02-17 => February 17th, 2011)

I'm aware of Chroni开发者_开发百科c, the Natural Language Parser for converting language into database calculating format, but I'm wondering how I can convert that data back into something humans can understand easily.

For example:

Chronic.parse('today') => 2011-02-17 17:30:00 -0500

So is there a way to take "2011-02-18 20:00:00 " and represent it as " Friday, February 18th, 2011 at 10pm "??

Essentially the reverse of Chronic?


Take a look at strftime, this is a link to it's implementation for the Time class.

With it you should be able to get the date to do anything you want :-)

>> Time.now.strftime("%A, %B %d, %Y at %l%p")
=> "Thursday, February 17, 2011 at  5PM"


http://api.rubyonrails.org/classes/DateTime.html#method-i-to_formatted_s

If you wanted to do the current date and time, just do:

Time.current.to_formatted_s(:long_ordinal)

to get:

February 17th, 2011 12:16

If you want to write your own formatting the api shows how you can do that in that link. Here's a list of the available formats:

%a  weekday name.
%A  weekday name (full).
%b  month name.
%B  month name (full).
%c  date and time (locale)
%d  day of month [01,31].
%H  hour [00,23].
%I  hour [01,12].
%j  day of year [001,366].
%m  month [01,12].
%M  minute [00,59].
%p  AM or PM
%S  Second [00,61]
%U  week of year (Sunday)[00,53].
w  weekday [0(Sunday),6].
W  week of year (Monday)[00,53].
x  date (locale).
%X  time (locale).
%y  year [00,99].
%Y  year [2000].
%Z  timezone name.

The only reason I recommend to_formatted_s over strftime is because with a good config/initializers/time_formats.rb, you can keep your views DRYer.


I was surprised there wasn't a "reverse of Chronic" gem, so I wrote one. It will work on your ActiveRecord objects.

Just gem install and call the 'pretty' method on your created_at field, or any other field with a class of ActiveSupport::TimeWithZone.

https://github.com/brettshollenberger/hublot

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜