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

问题描述 投票:48回答:5

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

ruby date datetime
5个回答
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

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的更多信息。


13
投票

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

我对上面不满意,所以我在阅读RUBY-DOC文档后的解决方案是:

获得10/31/2014的示例

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


0
投票

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

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


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")

这是另一种寻找方式

© www.soinside.com 2019 - 2024. All rights reserved.