Parsing dates

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?

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)

···

_________________________________________________________________
Bing™ brings you maps, menus, and reviews organized in one place. Try it now.

On Fri, Sep 25, 2009 at 1:38 AM, Ehsanul Hoque <ehsanul_g3@hotmail.com> wrot>

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