tags:

views:

149

answers:

4

With ruby I'm trying to get format a date as such: 2009-10-01

Where I take the current date (2009-10-26) and then change the day to "01".

I know of ways to do this, but was curious what the shortest way is, code wise, to pull this off.

+7  A: 
Time.parse("2009-10-26").strftime("%Y-%m-01")
Bob Aman
A: 
require 'date'    
now = Date.today
Date.new(now.year, now.month, 1)
CodeJoust
be careful with leading zeros in unquoted integers: that's octal notation. It'll work fine until you type 08 or 09.
jes5199
Fixed the now and the day problem. Thanks!
CodeJoust
A: 

This works...

Not terribly clever :/

require 'date'
Date.parse(Date.parse("2009-10-26").to_s[0,8] << "01")
SoreGums
A: 

If you don't mind including ActiveSupport in your application, you can simply do this:

require 'activesupport'
date = Date.today.beginning_of_month
PatrickTulskie