How to convert date in format 09-feb-73 to 02/09/1973 (mm/dd/yyyy开发者_StackOverflow中文版) using Ruby on Rails?
Valid Ruby datetime formats
Date.strptime("09-feb-73", "%d-%b-%y").strftime("%m/%d/%Y")
Note that strptime
is a part of Rails. And these are the relevant formats used:
%b - The abbreviated month name (``Jan'')
%d - Day of the month (01..31)
%m - Month of the year (01..12)
%y - Year without a century (00..99)
%Y - Year with century
You can do it with Date.parse
and Date#strftime
:
d = Date.parse('09-feb-73').strftime('%m/%d/%Y')
# "02/09/1973"
You could also use Date.strptime
instead of Date.parse
:
d = Date.strptime('09-feb-73', '%d-%b-%y').strftime('%m/%d/%Y')
# "02/09/1973"
The advantage of strptime
is that you can specify the format rather than leaving it to parse
to guess.
Date.strptime("09-feb-73", "%d-%b-%y").strftime("%m/%d/%Y")
Date Formats: http://snippets.dzone.com/posts/show/2255
If you require this in a view, I would suggest using localizations, since you can easily change the behavior based on your user's local settings and keep your controller code tidy (why should the controller care about the date format?). Example:
# config/locales/en.yml
en:
time:
formats:
short: "%m/%d/%Y"
# view file
<%=l Time.now, :format => :short %>
For more information on rails localizations, see the Rails Guide.
精彩评论