Question

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?

Was it helpful?

Solution

@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

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top