Marcos R. Guevara
Marcos R. Guevara

Reputation: 6388

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

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

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

Upvotes: 5

Views: 6610

Answers (2)

Stefan
Stefan

Reputation: 114158

Given a year and a month:

year = 2017
month = 5

You can pass these to Date.new along with a day value of 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 ...>

Upvotes: 13

user000001
user000001

Reputation: 33317

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

Upvotes: 12

Related Questions