Get last day of the month in Ruby

后端 未结 6 1566
-上瘾入骨i
-上瘾入骨i 2020-12-12 20:32

I made new object Date.new with args (year, month). After create ruby added 01 number of day to this object by default. Is there any way to add not first day, but last day o

相关标签:
6条回答
  • 2020-12-12 21:04

    So I was searching in Google for the same thing here...

    I wasn't happy with above so my solution after reading documentation in RUBY-DOC was:

    Example to get 10/31/2014

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

    0 讨论(0)
  • 2020-12-12 21:13

    To get the end of the month you can also use ActiveSupport's 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
    

    You can find out more on end_of_month in the Rails API Docs.

    0 讨论(0)
  • 2020-12-12 21:13
    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")
    

    This is another way to find

    0 讨论(0)
  • 2020-12-12 21:16

    This is my Time based solution. I have a personal preference to it compared to Date although the Date solutions proposed above read somehow better.

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

    btw for December you can see that year is not flipped. But this is irrelevant for the question because december always has 31 day. And for February year does not need flipping. So if you have another use case that needs year to be correct, then make sure to also change year.

    0 讨论(0)
  • 2020-12-12 21:17

    use Date.civil

    With Date.civil(y, m, d) or its alias .new(y, m, d), you can create a new Date object. The values for day (d) and month (m) can be negative in which case they count backwards from the end of the year and the end of the month respectively.

    => Date.civil(2010, 02, -1)
    => Sun, 28 Feb 2010
    >> Date.civil(2010, -1, -5)
    => Mon, 27 Dec 2010
    
    0 讨论(0)
  • 2020-12-12 21:20

    You can do something like that:

    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?
    
    0 讨论(0)
提交回复
热议问题