Ruby Date 1 month ago in String

I need to calculate the date 1 month from today in Ruby and convert it to Stringin the format:

yyyy-dd-mmThh: MM: ss (e.g. 2014-08-26T00: 00: 00)

I tried: (DateTime.now - Date.today.prev_month).to_datetime.strftime("%FT%T")but I get the method there are no exceptions.

+4
source share
3 answers

Try the following:

require 'date'

d = Date.today.prev_month # or Date.today.next_month, depending what you want
 => #<Date: 2014-12-27 ((2457019j,0s,0n),+0s,2299161j)> 
d.strftime("%FT%T")
 => "2014-12-27T00:00:00" 
+3
source

Try the following:

(DateTime.now - 1.month).strftime("%FT%T").to_s

PS: I'm sure this works great with rails. Please confirm that it works regardless of ruby ​​too?

UPDATE

As indicated below, this will only work if you have activesupportlib

+1
source

Try the following:

2.0.0-p247 :004 > require 'date'
 => false 
2.0.0-p247 :005 > Date.today.prev_month
 => #<Date: 2014-10-27 ((2456958j,0s,0n),+0s,2299161j)> 
2.0.0-p247 :006 > Date.today.prev_month.to_s
 => "2014-10-27" 
2.0.0-p247 :008 > Date.today.prev_month.strftime("%F%T")
 => "2014-10-2700:00:00" 
2.0.0-p247 :009 > 
+1
source

All Articles