[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

extending strftime

Lin Wj

1/13/2009 11:41:00 AM

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
--
Posted via http://www.ruby-....

2 Answers

Brian Candler

1/13/2009 12:14:00 PM

0

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.
--
Posted via http://www.ruby-....

Trans

1/13/2009 12:36:00 PM

0



On Jan 13, 6:41=A0am, Lin Wj <mailbox....@gmail.com> wrote:
> can i change the options which is recognized by strftime
> eg:
> '%Y %m %d' =A0will 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.