How do I set date time to 1 month ago with DateTime.now.strftime("%Y-%m-%d")?
Solution 1
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.
Solution 2
I realise this question is very old, but here's a clean way to do it for anyone who needs to know:
start_date = (Date.now - 30.days).strftime("%Y-%m-%d")
or
start_date = (Date.now - 1.month).strftime("%Y-%m-%d")
You can do similar things with DateTime.now
, and Time.now
Solution 3
With basic Ruby you can do this:
> irb
require 'date' # needed
today_minus_30 = Date.today.to_date - 30
# if you need the date as a string
date_as_string = today_minutes_30.strftime("%Y-%m-%d")
user2533139
Updated on June 15, 2022Comments
-
user2533139 almost 2 years
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 setstart_date
to 30 days ago.-
PJP almost 11 yearsWe need to see sample code showing what you've tried. See sscce.org
-
Topka almost 10 yearsProblem is not al moths are 30 days. Any solution for this, I wonder?
-
-
PJP almost 11 yearsYou might want to explain where
days
andago
come from and how they can be included. The OP is using straight Ruby so those aren't available. -
Powers almost 11 years@theTinMan - I agree with your comment and updated my answer accordingly. Thanks.
-
PJP almost 11 yearsNo, no, no, don't recommend loading the entire Active Support code base, just to cherry-pick a few needed methods. Use the core extensions for Date, DateTime and Time. Matter of fact, read "How to Load Core Extensions".
-
Powers almost 11 years@theTinMan - updated again and thanks for the comment. I couldn't get
require 'active_support/core_ext/date.rb'
to work, but found therequire 'active_support/time'
workaround on this thread: stackoverflow.com/questions/4238867/… Thanks! -
Geoff Williams over 5 yearsI think this needs
active_support/time
or rails?