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

11,342

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")
Share:
11,342
user2533139
Author by

user2533139

Updated on June 15, 2022

Comments

  • user2533139
    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 set start_date to 30 days ago.

    • PJP
      PJP almost 11 years
      We need to see sample code showing what you've tried. See sscce.org
    • Topka
      Topka almost 10 years
      Problem is not al moths are 30 days. Any solution for this, I wonder?
  • PJP
    PJP almost 11 years
    You might want to explain where days and ago come from and how they can be included. The OP is using straight Ruby so those aren't available.
  • Powers
    Powers almost 11 years
    @theTinMan - I agree with your comment and updated my answer accordingly. Thanks.
  • PJP
    PJP almost 11 years
    No, 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
    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 the require 'active_support/time' workaround on this thread: stackoverflow.com/questions/4238867/… Thanks!
  • Geoff Williams
    Geoff Williams over 5 years
    I think this needs active_support/time or rails?