Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current year and month (and next month) in this format YYYYMM in Ruby

Tags:

date

time

ruby

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.

like image 593
Hommer Smith Avatar asked Jun 08 '12 21:06

Hommer Smith


People also ask

How do I change the Date format in Ruby?

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.


Video Answer


2 Answers

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)>
like image 168
Michael Kohl Avatar answered Oct 19 '22 17:10

Michael Kohl


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
like image 17
Josh Avatar answered Oct 19 '22 18:10

Josh