A.7 Date

A.7.1 Creating a Date

To use the Date class in a Ruby program, we need to say:
require "date"
Note: Only Ruby programs need to have a require statement for the Date class. Rails already does this for you.

A.7.2 Date.new

Date.new ⇒ Date

Use the .new method to create a new instance of a Date object. The .new method can be used with or without argument. When given no arguments, the default date is set to Jan 1st, -4712 BCE.

Date.new                  # => #<Date: -4712-01-01 ((0j,0s,0n),+0s,2299161j)>
Date.new(2001)            # => #<Date: 2001-01-01 ...>
Date.new(2001,2,3)        # => #<Date: 2001-02-03 ...>
Date.new(2001,2,-1)       # => #<Date: 2001-02-28 ...>

Full explanation

A.7.3 Date.today

Date.today ⇒ Date

Initializes a Date object to the current date.

Returns a Date

Date.today # => #<Date: 2019-04-16 ((2458590j,0s,0n),+0s,2299161j)>

Full explanation

A.7.4 Date.parse()

Date.parse(String) ⇒ Date

Returns a Date object initialized to a date, interpreted from the given String argument.

Date.parse("2001-02-03")   # => #<Date: 2001-02-03 ...>
Date.parse("20010203")     # => #<Date: 2001-02-03 ...>
Date.parse("3rd Feb 2001") # => #<Date: 2001-02-03 ...>

Full explanation

A.7.5 Subtraction

Two dates can be subtracted from one another. The - operator returns a Rational which can be converted into an Integer to find the days in between the two dates.

number_of_days = Date.today - Date.parse("July 4, 1776") 
# => number_of_days = (88674/1)
number_of_days.to_i # => 88674

Full explanation

A.7.6 Date.mday

Date.mday ⇒ Integer

Returns the day of the month (1-31).

held_on = Date.new(2001,2,3)
held_on.mday # => 3

Full explanation

A.7.7 Date.wday

Date.wday ⇒ Integer

Returns the day of the week as an Integer (0-6, Sunday is 0).

held_on = Date.new(2001,2,3)
held_on.wday # => 6

Full explanation

A.7.8 Days of the Week

Date#moday? ⇒ Boolean

date = Date.new
date.monday?    # => true if date is a Monday.
date.tuesday?   # => true if date is a Tuesday.
date.wednesday? # => true if date is a Wednesday.
date.thursday?  # => true if date is a Thursday.
date.friday?    # => true if date is a Friday.
date.saturday?  # => true if date is a Saturday.
date.sunday?    # => true if date is a Sunday.

Returns a Boolean, true or false, if this given Date is a particular day of the week.

Full explanation