extending strftime

L

Lin Wj

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
 
B

Brian Candler

Lin said:
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 :eek:ld_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.
 
T

Trans

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,996
Messages
2,570,238
Members
46,826
Latest member
robinsontor

Latest Threads

Top