user2533139 user2533139 - 3 months ago 6
Ruby Question

How do I set date time to 1 month ago with DateTime.now.strftime("%Y-%m-%d")?

I am trying to use set Google Analytics start date and end date to capture unique visitors within the last 30 days. I have made

end_date = DateTime.now.strftime("%Y-%m-%d")
, how do I set
start_date
to 30 days ago.

Answer

The problem is you're going too far with your creation of end_date.

You're turning it into a string, which has no math capabilities. Instead, leave it as a DateTime and you inherit the ability to add and subtract integers to do date math:

require 'date'

datetime_now = DateTime.now
end_date = datetime_now.strftime("%Y-%m-%d") # => "2013-08-06"
end_date.class # => String

end_date = datetime_now # => #<DateTime: 2013-08-06T14:55:20-07:00 ((2456511j,78920s,731393000n),-25200s,2299161j)>
end_date - 30 # => #<DateTime: 2013-07-07T14:55:20-07:00 ((2456481j,78920s,731393000n),-25200s,2299161j)>

Notice that end_date - 30 returns a DateTime that is exactly 30 days earlier; The time component is preserved. Convert the value to a string once you have the value you want.