Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a Ruby date object from a string?

Tags:

date

ruby

How do I create a Ruby date object from the following string?

DD-MM-YYYY
like image 985
ben Avatar asked Aug 20 '10 09:08

ben


4 Answers

Date.parse('31-12-2010')

Alternatively Date#strptime(str, format).

like image 122
deceze Avatar answered Nov 20 '22 13:11

deceze


Because in the USA they get the dates backwards, it's important not to simply use Date.parse() because you'll find 9/11/2001 can be 11 September 2001 in the USA and 9 November 2001 in the rest of the world. To be completely unambiguous use Date::strptime(your_date_string,"%d-%m-%Y") to correctly parse a date string of format dd-mm-yyyy.

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

Also I always make sure I set my base timezone to :utc if my website is going to be handling any dates, and use Javascript on the client side to display local times.

like image 34
Dave Sag Avatar answered Nov 20 '22 15:11

Dave Sag


You can use Time#parse.

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

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

like image 18
Simone Carletti Avatar answered Nov 20 '22 13:11

Simone Carletti


If you have control over the format of the date in the string, then Date.parse works fine internationally with strings in YYYY-MM-DD (ISO 8601) format:

Date.parse('2019-11-20')
like image 3
Jon Schneider Avatar answered Nov 20 '22 13:11

Jon Schneider