如何使用Ruby on Rails将格式为09-feb-73的日期转换为1973年2月9日(mm / dd / yyyy)?
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 .
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.