Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a new Date instance in Ruby

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)
like image 296
Michael Durrant Avatar asked Sep 22 '12 14:09

Michael Durrant


People also ask

How do you create a Date object in Ruby?

A Date object is created with Date::new , Date::jd , Date::ordinal , Date::commercial , Date::parse , Date::strptime , Date::today , Time#to_date , etc. require 'date' Date. new(2001,2,3) #=> #<Date: 2001-02-03 ...> Date.

How do you parse a Date in Ruby?

Ruby | DateTime parse() function DateTime#parse() : parse() is a DateTime class method which parses the given representation of date and time, and creates a DateTime object. Return: given representation of date and time, and creates a DateTime object.


2 Answers

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 
like image 137
Sébastien Le Callonnec Avatar answered Oct 20 '22 11:10

Sébastien Le Callonnec


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 > 
like image 5
Houen Avatar answered Oct 20 '22 10:10

Houen