class Date

Class Date provides methods for storing and manipulating calendar dates.

Consider using class Time instead of class Date if:

  • You need both dates and times; Date handles only dates.

  • You need only Gregorian dates (and not Julian dates); see Julian and Gregorian Calendars.

A Date object, once created, is immutable, and cannot be modified.

Creating a Date ↑

You can create a date for the current date, using Date.today:

Date.today # => #<Date: 1999-12-31>

You can create a specific date from various combinations of arguments:

  • Date.new takes integer year, month, and day-of-month:

    Date.new(1999, 12, 31) # => #<Date: 1999-12-31>
    
  • Date.ordinal takes integer year and day-of-year:

    Date.ordinal(1999, 365) # => #<Date: 1999-12-31>
    
  • Date.jd takes integer Julian day:

    Date.jd(2451544) # => #<Date: 1999-12-31>
    
  • Date.commercial takes integer commercial data (year, week, day-of-week):

    Date.commercial(1999, 52, 5) # => #<Date: 1999-12-31>
    
  • Date.parse takes a string, which it parses heuristically:

    Date.parse('1999-12-31')    # => #<Date: 1999-12-31>
    Date.parse('31-12-1999')    # => #<Date: 1999-12-31>
    Date.parse('1999-365')      # => #<Date: 1999-12-31>
    Date.parse('1999-W52-5')    # => #<Date: 1999-12-31>
    
  • Date.strptime takes a date string and a format string, then parses the date string according to the format string:

    Date.strptime('1999-12-31', '%Y-%m-%d')  # => #<Date: 1999-12-31>
    Date.strptime('31-12-1999', '%d-%m-%Y')  # => #<Date: 1999-12-31>
    Date.strptime('1999-365', '%Y-%j')       # => #<Date: 1999-12-31>
    Date.strptime('1999-W52-5', '%G-W%V-%u') # => #<Date: 1999-12-31>
    Date.strptime('1999 52 5', '%Y %U %w')   # => #<Date: 1999-12-31>
    Date.strptime('1999 52 5', '%Y %W %u')   # => #<Date: 1999-12-31>
    Date.strptime('fri31dec99', '%a%d%b%y')  # => #<Date: 1999-12-31>
    

See also the specialized methods in “Specialized Format Strings” in Formats for Dates and Times

Argument limit ↑

Certain singleton methods in Date that parse string arguments also take optional keyword argument limit, which can limit the length of the string argument.

When limit is:

  • Non-negative: raises ArgumentError if the string length is greater than limit.

  • Other numeric or nil: ignores limit.