开发者

What is the cleanest way to remove beginning "0"'s from default dates in Ruby / Rails?

开发者 https://www.devze.com 2022-12-08 12:00 出处:网络
In /initializers/time_formats.rb I have this: Time::DATE_FORMATS[:profile] = \"%m /开发者_StackOverflow %d / %Y\"

In /initializers/time_formats.rb I have this:

Time::DATE_FORMATS[:profile] = "%m /开发者_StackOverflow %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?


@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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消