How to create a Ruby date object from a string?

How to create a Ruby date object from the following line?

DD-MM-YYYY 
+67
date ruby
Aug 20 '10 at 9:00
source share
6 answers
 Date.parse('31-12-2010') 

Alternatively Date#strptime(str, format) .

+126
Aug 20 '10 at 9:07
source share

Since they return dates in the US, it’s important not just to use Date.parse() , because September 11, 2001 may be September 11, 2001, and November 9, 2001 in the rest of the world. To be completely unique, use Date::strptime(your_date_string,"%d-%m-%Y") to properly parse the date string in dd-mm-yyyy format.

Try this to be sure:

 >irb >> require 'date' => true >> testdate = '11-09-2001' => "11-09-2001" >> converted = Date::strptime(testdate, "%d-%m-%Y") => #<Date: 4918207/2,0,2299161> >> converted.mday => 11 >> converted.month => 9 >> converted.year => 2001 

For other strptime formats see http://pubs.opengroup.org/onlinepubs/009695399/functions/strptime.html

I also always check if the base time zone is set to :utc if my website will process any dates and use client side Javascript to display local time.

+30
Sep 15 2018-11-11T00:
source share

You can use Time # parse .

 Time.parse("20-08-2010") # => Fri Aug 20 00:00:00 +0200 2010 

However, since Ruby can parse the date as "MM-DD-YYYY", the best way is to go with DateTime # strptime , where you can specify the input format.

+16
Aug 20 '10 at 9:05
source share

Similarly, you can get the Object time from a string as follows:

 t = Time.parse "9:00 PM" => 2013-12-24 21:00:00 +0530 t = Time.parse "12:00 AM" => 2013-12-24 00:00:00 +0530 

But Ruby parsed it like Date!

This way you can use the column as a row.

 add_column :table_name, :from, :string, :limit => 8, :default => "00:00 AM", :null => false add_column :table_name, :to, :string, :limit => 8, :default => "00:00 AM", :null => false 

And you can assign a string object to an attribute,

 r.from = "05:30 PM" r.save 

And parse the string to get a time object,

 Time.zone.parse("02:00 PM") 
+1
Dec 24 '13 at 12:16
source share

I find this approach simpler, as it should not specify a date format for the parser:

date1 = Time.local (2012, 1, 20, 12, 0, 0) .to_date

+1
Nov 22 '14 at 16:25
source share

Not necessarily for this string format, but it’s best to use the time parsing utility that I know of, Chronic , which is available as a gem and works about 99.9% of cases for human formatted dates / times.

0
Nov 11 '14 at 22:31
source share



All Articles