Get first and last day of month with Ruby (DateTime)

How can I get Retrieve the first and last day of the month with Ruby (DateTime)?

I want to create invoices that start on the first day and end on the last day of the month.

+3


source to share


2 answers


Use methods beginning_of_month

andend_of_month



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

      

+6


source


Given the year and month:

year = 2017
month = 5

      



You can pass them in Date.new

along with the daily value 1

and -1

to get the first and last day respectively:

require 'date'
Date.new(year, month, 1)  #=> #<Date: 2017-05-01 ...>
Date.new(year, month, -1) #=> #<Date: 2017-05-31 ...>

      

+4


source







All Articles