如何将日期字符串范围转换为datetime数据类型

时间:2015-01-28 09:50:19

标签: ruby-on-rails ruby

我需要将以下原始字符串(日期范围)转换为ruby datetime datetype。

如何在Rails上完成它?

原始字符串

"2014 April/July  24-1" 

转换为ruby datetime变量

start_date = 2014-04-24 
end_date = 2014-07-01

原始字符串

"2015 April  06-20"

转换为ruby datetime变量

start_date = 2015-04-06
end_date = 2015-04-20

1 个答案:

答案 0 :(得分:0)

这可能会有所帮助

# In order to generate
# year = 2014
# months = "April/July"
# days = "24-1"

/(?<year>\d{4})\s*(?<months>\w+\/\w+)\s*(?<days>\d{1,2}\-\d{1,2})/ =~ "2014 April/July  24-1"

date1 = "#{year} #{months.split('/')[0]} #{days.split('-')[0]}"
date2 = "#{year} #{months.split('/')[1]} #{days.split('-')[1]}"

start_date = Date.strptime(date1, "%Y %b %d") #=> Thu, 24 Apr 2014
end_date = Date.strptime(date2, "%Y %b %d")   #=> Tue, 01 Jul 2014