Getting current date

Hi,

How do I get the current date in the form “YYYY-MM-DD”.

Thanks, - Davegro

irb(main):005:0> Date.today.to_s
=> “2008-09-11”

See http://www.ruby-doc.org/core/classes/Date.html

On Sep 11, 9:38 pm, “DanDiebolt.exe” [email protected] wrote:

[Note: parts of this message were removed to make it a legal post.]

irb(main):005:0> Date.today.to_s
=> “2008-09-11”

Seehttp://www.ruby-doc.org/core/classes/Date.html

Thanks for this info and the link. I couldn’t find this on the linked
page, but what is an expression to get the current date minus one
month, in the same format as above?

  • Dave

On Fri, Sep 12, 2008 at 10:13 AM, laredotornado
[email protected] wrote:

Thanks for this info and the link. I couldn’t find this on the linked
page, but what is an expression to get the current date minus one
month, in the same format as above?

rails’s activesupport library has hammered on these issues extensively

  • it’s worth not reinventing the wheel

http://as.rubyonrails.com/

You can always copy bits of code if you don’t want to pull the library
in.

martin

On Fri, Sep 12, 2008 at 12:13 PM, laredotornado
[email protected] wrote:

month, in the same format as above?

  • Dave

In IRB…

require ‘date’
=> true
(Date.today << 1).to_s
=> 2008-8-12
#Be prepared for edge cases…
(Date.new(2008-3-31) << 1).to_s
=> 2008-2-29

Todd

My clunky way:

n = Time.now
d = Time.gm(n.year, n.month - 1, n.day)

p d

=> Tue Aug 12 00:00:00 UTC 2008

ok. Improvement time:

n = Time.now
if n.month == 12
d = Time.gm(n.year - 1, 12, n.day)
else
d = Time.gm(n.year, 1 - 1, n.day)
end

There has GOT to be a better way but I did not want you to have nothing.
:slight_smile:

dang typos

n = Time.now
if n.month == 1
d = Time.gm(n.year - 1, 12, n.day)
else
d = Time.gm(n.year, 1 - 1, n.day)
end

I put the testing code in and I feel REALLY stupid. If it is still
wrong, I am going to hide under a rock until everyone forgets that I did
this.

n = Time.now
if n.month == 1
d = Time.gm(n.year - 1, 12, n.day)
else
d = Time.gm(n.year, n.month - 1, n.day)
end

On Fri, Sep 12, 2008 at 3:02 PM, Lloyd L. [email protected]
wrote:

This also doesn’t handle edge cases like March 30/31, or October 31.


Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/

On Fri, Sep 12, 2008 at 1:13 PM, Todd B. [email protected]
wrote:

Thanks for this info and the link. I couldn’t find this on the linked
=> 2008-8-12
#Be prepared for edge cases…
(Date.new(2008-3-31) << 1).to_s
=> 2008-2-29

That was, of course supposed to be (Date.new(2008, 3, 31) <<
1).to_s, not Date.new(2008-3-31).

Note that the method is leap-year aware.

Todd