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?
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
Everything in ruby is open and extensible
class Time
def to_url_string
self.strftime("%H:%M:%s")
end
end
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.