在Ruby中获取本月的最后一天

时间:2013-01-02 10:45:27

标签: ruby date datetime

我使用args(年,月)创建了新对象Date.new。创建ruby后,默认情况下为此对象添加01天。有没有办法添加不是第一天,而是我作为arg传递的月份的最后一天(例如28如果它将是02个月或31如果它将是01个月)?

6 个答案:

答案 0 :(得分:92)

使用Date.civil

使用Date.civil(y, m, d)或其别名.new(y, m, d),您可以创建一个新的Date对象。日(d)和月(m)的值可以是负值,在这种情况下,它们分别从年末和月末倒计时。

=> Date.civil(2010, 02, -1)
=> Sun, 28 Feb 2010
>> Date.civil(2010, -1, -5)
=> Mon, 27 Dec 2010

答案 1 :(得分:59)

要获得月末,您还可以使用ActiveSupport的助手end_of_month

# Require extensions explicitly if you are not in a Rails environment
require 'active_support/core_ext' 

p Time.now.utc.end_of_month # => 2013-01-31 23:59:59 UTC
p Date.today.end_of_month   # => Thu, 31 Jan 2013

您可以在Rails API文档中找到有关end_of_month的更多信息。

答案 2 :(得分:14)

所以我在谷歌搜索同样的东西......

在阅读文档之后,我对上面的解决方案并不满意 在RUBY-DOC中:

获取10/31/2014

的示例

Date.new(2014,10,1).next_month.prev_day

答案 3 :(得分:0)

这是我基于Time的解决方案。与Date相比,我有个人偏好,尽管上面提出的Date解决方案在某种程度上更好。

reference_time ||= Time.now return (Time.new(reference_time.year, reference_time.month + 1) - 1).day

答案 4 :(得分:0)

require "date"
def find_last_day_of_month(_date)
 if(_date.instance_of? String)
   @end_of_the_month = Date.parse(_date.next_month.strftime("%Y-%m-01")) - 1
 else if(_date.instance_of? Date)
   @end_of_the_month = _date.next_month.strftime("%Y-%m-01") - 1
 end
 return @end_of_the_month
end

find_last_day_of_month("2018-01-01")

这是另一种查找方法

答案 5 :(得分:0)

您可以执行以下操作:

print(sub_lst)
['sun', ['water', 'air', 'fire', 'earth'], 'games', 2.7]