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")
The problem is you're going too far with your creation of
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)>
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.