views:

138

answers:

3

In /initializers/time_formats.rb I have this:

Time::DATE_FORMATS[:profile] = "%m / %d / %Y"

However this obviously produces dates such as: 09 / 08 / 2001

Google tells me my best bet is to use some kind of gsub regular expression to edit out the 0's. Is this true or is there a better alternative?

+2  A: 
@date = Time.new
@date.month #=> 10
@date.day   #=> 7
@date.year  #=> 2009

if you want to use format string for some parts, you can do something like:

@date.strftime("%B #{@date.day.ordinalize}, %Y") #=> October 7th, 2009
macek
nice so I combined both answers to get @date.strftime("#{@date.month} / %e / %Y"). Seems a little silly that the strftime does not come with something like %e for months. I am sure that there is a good reason, but considering the time constraints, I don't have time to think about it. no pun intended. ok maybe.
drpepper
+1  A: 

You could probably use '%e' to get the day number without the leading zero; however, the manual page for 'strftime()' - which usually underlies these time-based conversions - does not show a way to do that for the months, so the regex solution is perhaps one way to do it, though there might be other more Ruby-idiomatic ways to achieve the equivalent result.

Jonathan Leffler
regex here would be going against the grain a bit. There's other more intuitive things that can be done before resorting to using regex.
macek
thanks Jon - I added this bit the solution!
drpepper
@smotchkiss - I'll modify the answer to qualify the regex from 'probably necessary'...
Jonathan Leffler
A: 

You can use a lambda/proc as a format in Time::DATE_FORMATS, e.g.

Loading development environment (Rails 2.3.4)
>> Time::DATE_FORMATS[:my_format] = lambda { |time| "#{time.day}/#{time.month}/#{time.year}" }
=> #<Proc:0x000000010341a2e0@(irb):3>
>> 2.months.ago.to_s(:my_format)
=> "8/8/2009"

Note that the default Time::DATE_FORMATS uses a lambda for both the :long_ordinal and :rfc822 formats.

pixeltrix