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.
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
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
© 2024 OneMinuteCode. All rights reserved.