44

How can I create a new Date object in IRB with a given date. The following didn't work.

1.9.3p194 :053 > require 'active_support'
 => true 
1.9.3p194 :054 > Date.new
 => #<Date:0x9d80730> 
1.9.3p194 :055 > Date.parse('12/01/2012')
NoMethodError: undefined method `parse' for Date:Class
        from (irb):55

1.9.3p194 :055 > Date.new('12/01/2012')
ArgumentError: wrong number of arguments(1 for 0)
Michael Durrant
  • 93,410
  • 97
  • 333
  • 497

7 Answers7

52

According to Date documentation:

require 'date'

Date.new(2001,2,25)           #=> #<Date: 2001-02-25 
Date.jd(2451966)             #=> #<Date: 2001-02-25 
Date.ordinal(2001,56)        #=> #<Date: 2001-02-25 
Date.commercial(2001,8,7)    #=> #<Date: 2001-02-25 
Date.parse('2001-02-25')     #=> #<Date: 2001-02-25 
Date.strptime('25-02-2001', '%d-%m-%Y') #=> #<Date: 2001-02-25 
Time.new(2001,2,25).to_date   #=> #<Date: 2001-02-25 
Michael Durrant
  • 93,410
  • 97
  • 333
  • 497
Sébastien Le Callonnec
  • 26,254
  • 8
  • 67
  • 80
4
1.9.3-p125 :012 > require 'date'
 => true 
1.9.3-p125 :013 > Date::new(2012,02,03)
 => #<Date: 2012-02-03 ((2455961j,0s,0n),+0s,2299161j)> 
1.9.3-p125 :014 > 
Houen
  • 1,039
  • 1
  • 16
  • 35
3

I find the following easier to remember than Date.new:

require 'active_support/core_ext/string'
'2019-03-31'.to_date
=> #<Date: 2019-03-21 ((2458564j,0s,0n),+0s,2299161j)>

See https://apidock.com/rails/String/to_date

Jon Schneider
  • 25,758
  • 23
  • 142
  • 170
jethro
  • 168
  • 3
  • 13
2

If you're trying to get active_support extensions to Date outside of Rails, you'll have to use the core_ext module:

require 'active_support/core_ext/date/calculations'
Date.parse('12/01/2012')
=> #<Date: 2012-01-12 ((2455939j,0s,0n),+0s,2299161j)>

More info in this Rails guide: http://edgeguides.rubyonrails.org/active_support_core_extensions.html

rossta
  • 11,394
  • 1
  • 43
  • 47
0
Date.strptime("2012-09-21 19:45:48","%Y-%m-%d %H:%M:%S")
saihgala
  • 5,724
  • 3
  • 34
  • 31
0

You need to use the date extension from the Ruby Standard Library. Most examples in the docs don't always show you to require it.

require 'date'

was what you needed. It's not a built in set of Classes or Modules.

You get two Classes with that addition,

Date
DateTime

And with that you may now use info found in the docs

Douglas G. Allen
  • 2,203
  • 21
  • 20
0
require 'date'
Date::strptime("29-05-2017", "%d-%m-%Y")

So, you need to include this date module in your code and then use the method strptime inside which you may notice for year, I have used capital Y because full year is entered as the first parameter of the strptime method. You can use small y if the date is like '29-05-17'.

Akhil Gautam
  • 169
  • 1
  • 10