Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Date 1 month ago to String

Tags:

date

ruby

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

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

I have tried: (DateTime.now - Date.today.prev_month).to_datetime.strftime("%FT%T") but I get a method does not exist exception.

like image 243
Eduardo Avatar asked Nov 27 '14 12:11

Eduardo


4 Answers

Try this:

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" 
like image 184
dax Avatar answered Oct 10 '22 20:10

dax


Try this:

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 > 
like image 24
Michael Durrant Avatar answered Oct 10 '22 21:10

Michael Durrant


Try this:

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

PS: I am sure this works fine with rails. Please confirm if it works independently on ruby too?

UPDATE:

As pointed out on comment below, this will work only if you have activesupport lib

like image 20
shivam Avatar answered Oct 10 '22 20:10

shivam


UPDATE 2021

You can write this, for simplicity:

1.month.ago.beginning_of_month.to_s

# Or

1.month.ago.end_of_month.to_s
like image 39
Shannarra Avatar answered Oct 10 '22 21:10

Shannarra