如何获得红宝石下个月的第一天?

max*_*rez 53 ruby-on-rails

我有一个营业日期.我想要创建已经获得的期票:

day=1
month= the next month of operation_date
year= automatic
Run Code Online (Sandbox Code Playgroud)

示例:

operation_date = 15/11/2010 
promissory_note1_date = 1/12/2010
promissory_note2_date = 1/01/2011
promissory_note3_date = 1/02/2011
promissory_note4_date = 1/02/2011
Run Code Online (Sandbox Code Playgroud)

如果存在四张期票

我该怎么做?

PD:对不起我的语法

jor*_*inl 157

你可以做

require "active_support"

Date.today.at_beginning_of_month
#=> Wed, 01 Dec 2010

Date.today.at_beginning_of_month.next_month
#=> Sat, 01 Jan 2011

Date.today.at_beginning_of_month.next_month.next_month
#=> Tue, 01 Feb 2011
Run Code Online (Sandbox Code Playgroud)

等等...

  • `on_beginning_of_month`等由ActiveSupport提供,因此可以在Rails中使用,但不能在纯Ruby中使用. (27认同)
  • 只是为了澄清:这不是纯 Ruby 而是 Rails 扩展的一部分,您需要 `require "active_support/core_ext"` 才能使其正常工作 (2认同)

Sag*_*ani 13

如果您不使用rails或不想要求active_support,我发现没有active_support的更简单的方法

(Date.today - Date.today.mday + 1) # First day of the current month
=> Thu, 01 Dec 2016
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!:-)

  • 很好,谢谢.没有+1它是上个月的最后一个,这也很好:) (3认同)

Jer*_*ome 9

N个月的一般回复

(Date.today + N.months).at_beginning_of_month
Run Code Online (Sandbox Code Playgroud)

  • 在普通 Ruby 中不起作用的“通用”响应。 (3认同)

bog*_*ggy 8

我的解决方案

class Time
  def start_of_next_month
    Time.local(self.year + self.month / 12, self.month % 12 + 1)
  end
end
Run Code Online (Sandbox Code Playgroud)


ran*_*dra 7

我使用Ruby 1.8.71.9.2rvm在两种情况下Date.today会导致一个错误:

ruby-1.8.7-p302 > Date.today
NameError: uninitialized constant Date

ruby-1.9.2-p0 > Date.today
NameError: uninitialized constant Object::Date
Run Code Online (Sandbox Code Playgroud)

我应该使用的东西Time.now ,这个链接应该帮助你http://pleac.sourceforge.net/pleac_ruby/datesandtimes.html.

我不确定at_beginning_of_monthruby 中方法的可用性,但它确实存在于RoR中.

  • ruby-1.8.7-p302> require'date'将解决NameError问题,Date.today将起作用 (9认同)

bog*_*ggy 5

对于那些使用Time class的人:

class Time
        def start_of_next_month
                t = Time.local(self.year,self.month)+45*24*3600;
                Time.local(t.year,t.month)
        end
end
Run Code Online (Sandbox Code Playgroud)

我知道这有点笨拙:)