Your code does explain what’s going on. Time.parse is not returning
what you would expect because you are passing in just the String
representation of a month (rather than of a complete date). An easy
way to make it do what you want is to tack on a day to the end of the
string.
For instance (in IRB):
Time.parse(“03”)
=> Sat Jun 02 12:46:40 CDT 2007
Time.parse(“04”)
=> Sat Jun 02 12:46:44 CDT 2007
Time.parse(“03/01”)
=> Thu Mar 01 00:00:00 CST 2007
Time.parse(“04/01”)
=> Sun Apr 01 00:00:00 CDT 2007
Your code does explain what’s going on. Time.parse is not returning
what you would expect because you are passing in just the String
representation of a month (rather than of a complete date). An easy
way to make it do what you want is to tack on a day to the end of the
string.
For instance (in IRB):
Time.parse(“03”)
=> Sat Jun 02 12:46:40 CDT 2007
Time.parse(“04”)
=> Sat Jun 02 12:46:44 CDT 2007
Time.parse(“03/01”)
=> Thu Mar 01 00:00:00 CST 2007
Time.parse(“04/01”)
=> Sun Apr 01 00:00:00 CDT 2007
Time.parse(“04/01”).strftime("%b")
=> “Apr”
I hope this helps,
David
Thanks, That kind of weird, I just added a year and it helps. Why is
that? Since I’m passing it different month number as a string, shouldn’t
it look at them as separate numbers as strings?
Thanks, That kind of weird, I just added a year and it helps. Why is
that? Since I’m passing it different month number as a string,
shouldn’t
it look at them as separate numbers as strings?
Well, the problem is that when you only pass Time.parse a single
number, it does not know how to interpret that. Is it a month? A
year? A day? There’s no real way to tell. The way Time.parse works is
it tries to match the string you pass in against a series of
patterns. Most of the time, it does what you want. (i.e., if a person
could tell how to interpret the string as a date, Time.parse probably
will be able to as well). The exact details of how it does the
matching, however, are complex. The best place to look is probably
the source code – see the _parse method in date/format.rb in the
standard libs if you want to see exactly what it’s doing – there’s a
lot of code there, but it’s pretty readable, as long as you grok
regular expressions.