views:

66

answers:

4

For instance, if I have a Time.now, how would I convert that to a friendly url string?

Time.now.some_method_here => some_url_friendly_string_here

I believe there is a built-in Ruby method to do so, but I can't seem to locate it on Google. Any ideas?

+2  A: 

You can use the strftime method. It's a bit cryptic, but if you look at the docs, you can pick out the year, month, day, etc.

For example, Time.now.strftime("%H:%M:%s") will give the time in hours, minutes and seconds.

AboutRuby
Thanks for the link and the tip!
sjsc
+2  A: 

Everything in ruby is open and extensible

class Time
  def to_url_string
    self.strftime("%H:%M:%s")
  end
end
Jarrett Meyer
I love this one
PeterWong
Appreciate it Jarrett. Thank you!
sjsc
+1  A: 

You might consider using the xmlschema method which will return a date/time in the format:

CCYY-MM-DDThh:mm:ssTZD

or

CCYY-MM-DDThh:mm:ss.sssTZD

depending on the value of the fraction_digits argument.

This would give you a time like:

2010-09-15T20:31:15+05:00

for example.

See the docs for more info and a link to the code.

tvanfosson
Thank you so much :)
sjsc
+4  A: 

As you're using Rails (as indicated by your tag), you can use .to_s:

Time.now.to_s

You can specify a time format to the method, which will format the string differently, such as Time.now.to_s(:db). Please see this link for the default date formats. If you don't specify a format, it'll use the same as strftime.

The next part of that page also describes how to add your own time formats, which is very simple:

# Initializer
Time::DATE_FORMATS[:month_and_year] = "%B %Y"

# Any code
Time.now.to_s(:month_and_year) # => September 2010
vonconrad
Thank you so much Von!
sjsc