Really quick question - How do I convert a string to a date

G

Glenn Smith

I need a 'Date' object which is converted from a string value
containing something like '13/04/2005' (english format date).

Help!
 
J

James Edward Gray II

I need a 'Date' object which is converted from a string value
containing something like '13/04/2005' (english format date).

Help!

This isn't a particularly brilliant answer, so hopefully someone will
do better:

ruby -r date -e 'puts Date.parse("13/04/2005".split("/").values_at(1,
0, 2).join("/"))'

Hope that helps.

James Edward Gray II
 
W

WATANABE Hirofumi

Hi,

Glenn Smith said:
I need a 'Date' object which is converted from a string value
containing something like '13/04/2005' (english format date).

% ruby -rdate -e 'puts Date.strptime("13/04/2005", "%d/%m/%Y")'
2005-04-13
 
J

James Edward Gray II

Hi,



% ruby -rdate -e 'puts Date.strptime("13/04/2005", "%d/%m/%Y")'
2005-04-13

I knew there had to be a clever solution. Nice!

James Edward Gray II
 
N

Neil Stevens

I need a 'Date' object which is converted from a string value
containing something like '13/04/2005' (english format date).

Help!

If you're certain it's that date format:

require 'date'
parts = '13/04/2005'.split('/').reverse
parts = parts.collect do |i|
i = i.to_i
end
date = Date.new(*parts)
 
G

Glenn Smith

It was exactly this problem I was having Neil (ie. using ParseDate on
'13/04'2005' gave me an error - I think it didn't like there being 13
months!)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top