How do I get the current date and month in Ruby in a specific format?
If today is June, 8th of 2012, I want to get 201206
.
And also, I would like to be able to get the next month from the one we are in, taking into account that in 201212, the next month would be 201301.
Two steps: You need to convert your string into Date object. For that, use Date#strptime . You can use Date#strftime to convert the Date object into preferred format.
I'd do it like this:
require 'date'
Date.today.strftime("%Y%m")
#=> "201206"
(Date.today>>1).strftime("%Y%m")
#=> "201207"
The advantage of Date#>> is that it automatically takes care of certain things for you:
Date.new(2012,12,12)>>1
#=> #<Date: 2013-01-12 ((2456305j,0s,0n),+0s,2299161j)>
Current month:
date = Time.now.strftime("%Y%m")
Next month:
if Time.now.month == 12
date = Time.now.year.next.to_s + "01"
else
date = Time.now.strftime("%Y%m").to_i + 1
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With