Get last day of the month in Ruby

Get last day of the month in Ruby

Asked on December 28, 2018 in Ruby.
Add Comment


  • 6 Answer(s)

    Try to use  Date.civil function,

    We can create a new Date object ,with Date.civil(y, m, d) or its alias .new(y, m, d). In the case which these count are backwards can be negative.

    => Date.civil(2010, 02, -1)
    => Sun, 28 Feb 2010
    >> Date.civil(2010, -1, -5)
    => Mon, 27 Dec 2010
    
    Answered on December 28, 2018.
    Add Comment

    Try to 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
    

    For more reference about end of month in Rails API Docs.

    Answered on December 28, 2018.
    Add Comment

    Simply use this one line code,

    Date.new(2014,10,1).next_month.prev_day
    
    Answered on December 28, 2018.
    Add Comment

    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 of month that i passed as arg(e.g. 28 if it will be 02month or 31 if it will be 01month) ?

    Answered on May 20, 2019.
    Add Comment
     Date.civil(2010, 02, -1)
    => Sun, 28 Feb 2010
    >> Date.civil(2010, -1, -5)
    => Mon, 27 Dec 2010
    Answered on May 20, 2019.
    Add Comment

    This is probably an easy one for somebody, but I couldn’t figure it out
    using the Date class in the documentation.

    require ‘date’

    d = Date.new(2006, 9,16)

    How do I return the date for the last day of this month (September in
    this example)?

    Thank you for your help!

    Answered on May 20, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.