Forum: Ruby extending strftime

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Lin W. (Guest)
on 2009-01-13 13:42
can i change the options which is recognized by strftime
eg:
'%Y %m %d'  will apply the format of YYYY mm dd

can i do something like extending strftime to recognize 'YYYY mm dd'
instead ?

because right now , i am running the format string which i get(YYYY mm
dd) through a regex and converting them to the parameters which strftime
recognizes

or please do suggest alternate methods
Brian C. (Guest)
on 2009-01-13 14:14
Lin Wj wrote:
> can i change the options which is recognized by strftime
> eg:
> '%Y %m %d'  will apply the format of YYYY mm dd
>
> can i do something like extending strftime to recognize 'YYYY mm dd'
> instead ?
>
> because right now , i am running the format string which i get(YYYY mm
> dd) through a regex and converting them to the parameters which strftime
> recognizes

That sounds like a perfectly reasonable approach.

If you really want to, you can monkey-patch the built-in class (I'd
advise against this though, except in small self-contained scripts)

class Time
  alias :old_strftime :strftime
  STRFMAP = {
    'YYYY' => '%Y',
    'mm' => '%m',
    'dd' => '%d',
  }
  STRFRE = /#{STRFMAP.keys.join("|")}/

  def strftime(arg)
    old_strftime(arg.gsub(STRFRE) { STRFMAP[$&] })
  end
end

puts Time.now.strftime("YYYY-mm-dd")

Note that by not using the % escape syntax, you may end up with some
subtle bugs:

puts Time.now.strftime("Today's YYYY-mm-dd, buddy!")
# => Today's 2009-01-13, bu13y!

You can restrict the regular expression to require a word boundary:

  STRFRE = /\b(#{STRFMAP.keys.join("|")})\b/

But in this case, a string like "YYYYmmdd" doesn't work.
Thomas S. (Guest)
on 2009-01-13 14:37
(Received via mailing list)
On Jan 13, 6:41 am, Lin Wj <removed_email_address@domain.invalid> wrote:
> can i change the options which is recognized by strftime
> eg:
> '%Y %m %d'  will apply the format of YYYY mm dd
>
> can i do something like extending strftime to recognize 'YYYY mm dd'
> instead ?

why not write your own Time method? you don't need to override
strftime.

> because right now , i am running the format string which i get(YYYY mm
> dd) through a regex and converting them to the parameters which strftime
> recognizes
>
> or please do suggest alternate methods

T.
This topic is locked and can not be replied to.