Parsing dates

R

Rong

When I do this:

dob="05/01/1968"
x=Date.parse(dob)
x.month

I get 1 instead of 5.
How do I do this?
 
E

Ehsanul Hoque

When I do this:
=20
dob=3D"05/01/1968"
x=3DDate.parse(dob)
x.month
=20
I get 1 instead of 5.
How do I do this?
=20

Well=2C it's not a bug or something. The rest of the world uses day/month/y=
ear so that is the default that the Date.parse method uses.

The easiest solution (and the best way to do this IMO) is to just feed the =
method "01/05/1968" instead of "05/01/1968".

If for some reason=2C you HAVE to have the m/d/y format=2C you could just u=
se a regexp. Could be something like this=2C but note=2C it's not really th=
e best regexp=2C just something I came up with now (you can use rubular.com=
to figure out ruby regexps easily):

dob =3D "05/01/1968"
dob =3D~([01]\d)\/([0-3]\d)\/((19|20)\d\d) =0A=
_________________________________________________________________=0A=
Bing=99 brings you maps=2C menus=2C and reviews organized in one place. =
Try it now.=0A=
http://www.bing.com/search?q=3Drestaurants&form=3DMLOGEN&publ=3DWLHMTAG&cre=
a=3DTEXT_MLOGEN_Core_tagline_local_1x1=
 
R

Rick DeNatale

When I do this:

dob="05/01/1968"
x=Date.parse(dob)
x.month

I get 1 instead of 5.
How do I do this?

Well, it's not a bug or something. The rest of the world uses day/month/year so that is the default that the Date.parse method uses.

The easiest solution (and the best way to do this IMO) is to just feed the method "01/05/1968" instead of "05/01/1968".

If for some reason, you HAVE to have the m/d/y format, you could just use a regexp. Could be something like this, but note, it's not really the best regexp, just something I came up with now (you can use rubular.com to figure out ruby regexps easily):

dob = "05/01/1968"
dob =~([01]\d)\/([0-3]\d)\/((19|20)\d\d)

Or better, IMHO, use strptime

require 'date'
d = Date.strptime("05/01/1968", "%m/%d/%Y")

d.month #=> 5
d.day #=> 1
d.year #=> 1968

Works for DateTime as well as Date

--
Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale
 

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

Forum statistics

Threads
474,168
Messages
2,570,914
Members
47,455
Latest member
Delilah Code

Latest Threads

Top