Get Last Day of the Month in Ruby

Get last day of the month in Ruby

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

Retrieve first and last day of the month with Ruby (DateTime)

Use the beginning_of_month and end_of_month methods

irb(main):004:0> n = DateTime.now
=> Wed, 10 May 2017 14:48:01 +0300
irb(main):005:0> n.to_date.beginning_of_month
=> Mon, 01 May 2017
irb(main):006:0> n.to_date.end_of_month
=> Wed, 31 May 2017

Ruby: how to Last day of last month

Anything like this?

require 'date'

t = Date.today
Date.new(t.year, t.month) - 1
=> #<Date: 2016-10-31 ((2457693j,0s,0n),+0s,2299161j)>

How to check day is last date of month in ruby

I would do something like this

def is_last_day(mydate)
mydate.month != mydate.next_day.month
end

Getting the first and last day of a month in ruby from partial string

Since you know the month and year already you have solved half of your problem already because each month begins with the 1st.

You can use that to build an initial date and then you can call end_of_month to do the heavy lifting for you.

month = 4
year = 2016
beginning_of_month = "#{year}-#{month}-01".to_date
end_of_month = beginning_of_month.end_of_month

get next/previous month from a Time object

There are no built-in methods on Time to do what you want in Ruby. I suggest you write methods to do this work in a module and extend the Time class to make their use simple in the rest of your code.

You can use DateTime, but the methods (<< and >>) are not named in a way that makes their purpose obvious to someone that hasn't used them before.

How can I get the 15th and last day of each month?

I'm not sure if this will work with Rails 4:

start_date = Date.today
# => Wed, 06 Nov 2013
mid_month = (start_date + 1.month).beginning_of_month + 14
# => Sun, 15 Dec 2013
end_month = (start_date + 1.month).end_of_month
# => Tue, 31 Dec 2013


Related Topics



Leave a reply



Submit