在ruby中使用月份名称计算月份数
在ruby中,如何使用他们的名字计算两个月之间的月数 示例:在ruby中使用月份名称计算月份数,ruby,Ruby,在ruby中,如何使用他们的名字计算两个月之间的月数 示例: Feb to Oct => 9 Dec to Mar => 4 Apr to Aug => 5 如何实现这一点?Use可以使用DateTime::StrTime获取表示一年中月份顺序的数字。从那里开始应该很容易 require 'date' def distance(start_month, end_month) distance = DateTime.strptime(end_month,"%b").mon
Feb to Oct => 9
Dec to Mar => 4
Apr to Aug => 5
如何实现这一点?Use可以使用DateTime::StrTime获取表示一年中月份顺序的数字。从那里开始应该很容易
require 'date'
def distance(start_month, end_month)
distance = DateTime.strptime(end_month,"%b").month - DateTime.strptime(start_month,"%b").month + 1
distance < 0 ? distance + 12 : distance
end
需要“日期”
def距离(开始月、结束月)
距离=DateTime.strTime(结束月份,“%b”)。月份-DateTime.strTime(开始月份,“%b”)。月份+1
距离<0?距离+12:距离
结束
您可以定义一个包含12个元素的数组,其中包含您可能的月份名称。然后,当您需要查找month1
和month2
之间的月数时,您需要查找它们的索引,可能需要使用散列
,如下所示:
#let month1 and month2 be the values
array = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
hash = Hash[array.map.with_index.to_a] # => {"a"=>0, "b"=>1, "c"=>2}
#(hash[month2] + 12 - hash[month1]) % 12 should yield the desired result
require 'date'
month1 = Date.parse("Feb").month
month1 = Date.parse("Apr").month
但是,上述解决方案不涉及年份。如果month1
是'Jan'
,month2
是'Feb'
,那么无论month1
的年份和month2
的年份,结果都将是1
我对Ruby不太精通,因此我的代码的语法可能有错误。如果您有月份名称,则可以解析该月份并获取该月份的序列号,如下所示:
#let month1 and month2 be the values
array = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
hash = Hash[array.map.with_index.to_a] # => {"a"=>0, "b"=>1, "c"=>2}
#(hash[month2] + 12 - hash[month1]) % 12 should yield the desired result
require 'date'
month1 = Date.parse("Feb").month
month1 = Date.parse("Apr").month
或者您可以使用12个月的数组来查找它们的序列号。
对于月与月之间的计数:
result = ((month2 > month1) ? (month2 - month1) : (month1 - (month1 - month2)) + 1)
这将在每个月的顺序中起作用。如果month1 id为'Dec'而month2 id为'Mar',那么它将返回计数4,而不是9。问题不清楚。添加更多详细信息。感谢您的回复,使用此选项,我将得到12个12月和2个2月。然后,如果您想处理今年的12月到明年的2月,我将如何获得它们之间的计数,如果结果为负,你可以加上12:2-12+1=-9,-9+12=3如果我得到12(Dec)作为一个开始月,你的代码我会得到10作为Dec到3月的结果,你怎么调用这个函数:距离(“Dec”,“Mar”)=>4i也需要考虑一年,因为从DEC到FEB,我应该得到3的结果,这已经在我的代码中处理了。考虑到这一年,我的意思是从2012年12月到2014年2月,你有15个月,而不是3个月。请用Dec和Feb测试我的代码。结果是否也需要+1?我不理解这个问题
def months_between( start_month, end_month)
month_names = %w[ Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ]
(12 + month_names.index( end_month ) - month_names.index( start_month ) ) % 12 + 1
end