How to get the last day of this month from Ruby

Asked 2 years ago, Updated 2 years ago, 49 views

The code is now like this.

Date.new(Time.now.year, Time.now.month, -1).day

I think I can write smarter...

Please let me know if there is any other way to write.

To put it further, I use it to determine whether today is the last day.
I would appreciate it if you could let me know if there is a suitable way for this.

ruby

2022-09-30 18:33

2 Answers

This is Ruby, so there should be another way to write Date.new(Time.now.year, Time.now.month, -1).day is quite easy to read and is a very popular way to write .There seems to be another approach, but I don't think the function in this case is easier to read than the original approach.

Also, if you want to use Rails itself, I think there is a function called end_of_month().

As yasu explained, there is also an option for ActiveSupport.Come to think of it, there seems to be a gem called expanded_date.

Example of expanded_date (Example based on Jon's thread):

require 'expanded_date'

d = Date.today
puts d.end_of_month.mday.to_s

The output is:

31


2022-09-30 18:33

There is a way to use ActiveSupport's Date# at_end_of_month (Time# at_end_of_month).(There should be no standard way to write smartly.)

require "active_support/all"

Date.today.at_end_of_month
# =>Thu, 31 Mar 2016


2022-09-30 18:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.