57

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

4

6 回答 6

108

利用Date.civil

使用Date.civil(y, m, d)或其 alias .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
于 2013-01-02T10:49:16.520 回答
76

要获得月底,您还可以使用 ActiveSupport 的 helper 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的信息。

于 2013-01-02T11:59:48.290 回答
17

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

我对上述内容不满意,因此在阅读RUBY-DOC中的文档后我的解决方案是:

获取示例10/31/2014

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

于 2014-10-10T21:28:42.967 回答
0

你可以这样做:

def last_day_of_month?
   (Time.zone.now.month + 1.day) > Time.zone.now.month
end

Time.zone.now.day if last_day-of_month?
于 2020-02-18T05:51:25.787 回答
0

这是我Time的基础解决方案。与上面提出的解决方案相比,我有个人偏好,Date尽管Date上面提出的解决方案读起来更好。

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

顺便说一句,十二月你可以看到那一年没有翻转。但这与问题无关,因为 12 月总是有 31 天。并且对于二月年不需要翻转。因此,如果您有另一个需要正确年份的用例,请确保也更改年份。

于 2018-05-18T13:48:00.913 回答
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")

这是另一种查找方式

于 2018-06-27T12:40:45.870 回答