Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm aware of Chronic, 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?

like image 719
ChrisWesAllen Avatar asked Feb 17 '11 16:02

ChrisWesAllen


People also ask

How do I change the date format in Ruby on Rails?

For that, use Date#strptime . You can use Date#strftime to convert the Date object into preferred format.

How do you parse time in Ruby?

Ruby | DateTime parse() function DateTime#parse() : parse() is a DateTime class method which parses the given representation of date and time, and creates a DateTime object. Return: given representation of date and time, and creates a DateTime object.

Is DateTime deprecated Ruby?

DateTime is considered deprecated. It only still exists to be backwards-compatible. As of Ruby 3 (released December 24th, 2020, as is Ruby tradition), DateTime only exists for backwards-compatibility. The date library docs recommend you just use Time instead.


1 Answers

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"
like image 190
Bitterzoet Avatar answered Oct 04 '22 16:10

Bitterzoet