加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 将字符串日期格式从“2011年11月17日”转换为“11/17/11

发布时间:2020-12-16 19:49:38 所属栏目:百科 来源:网络整理
导读:我有这个代码将日期字符串数组从2011年11月17日的格式转换为11/17/11: def date_convert dates months = { 'Jan' = 1,'Feb' = 2,'Mar' = 3,'Apr' = 4,'May' = 5,'Jun' = 6,'Jul' = 7,'Aug' = 8,'Sep' = 9,'Oct' = 10,'Nov' = 11,'Dec' = 12 } new_dates = [
我有这个代码将日期字符串数组从2011年11月17日的格式转换为11/17/11:
def date_convert dates
  months = { 'Jan' => 1,'Feb' => 2,'Mar' => 3,'Apr' => 4,'May' => 5,'Jun' => 6,'Jul' => 7,'Aug' => 8,'Sep' => 9,'Oct' => 10,'Nov' => 11,'Dec' => 12 }
  new_dates = []
  dates.each do |date|
    date_split = date.split('-')
    month = months[date_split[1]] 
    day = date_split[0]
    year = date_split[2][-2,2]
    new_dates.push ("#{month}/#{day}/#{year}")
  end
  new_dates
end

有没有更好的,可能内置的方法来进行这种转换与Ruby?我正在学习Ruby,所以任何其他的方法将不胜感激.

解决方法

使用内置的Time.parse和Time#strftime函数.
require 'time'
time = Time.parse("17-Nov-2011")
time.strftime("%m/%d/%y")
# => "11/17/11"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读