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 ...>
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)>
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 ...>
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.
Date.today - Date.parse("July 4, 1776")
number_of_days = # => number_of_days = (88674/1)
# => 88674 number_of_days.to_i
A.7.6 Date.mday
Date.mday ⇒ Integer
Returns the day of the month (1-31).
Date.new(2001,2,3)
held_on = # => 3 held_on.mday
A.7.7 Date.wday
Date.wday ⇒ Integer
Returns the day of the week as an Integer
(0-6, Sunday is 0).
Date.new(2001,2,3)
held_on = # => 6 held_on.wday
A.7.8 Days of the Week
Date#moday? ⇒ Boolean
Date.new
date = # => true if date is a Monday.
date.monday? # => true if date is a Tuesday.
date.tuesday? # => true if date is a Wednesday.
date.wednesday? # => true if date is a Thursday.
date.thursday? # => true if date is a Friday.
date.friday? # => true if date is a Saturday.
date.saturday? # => true if date is a Sunday. date.sunday?
Returns a Boolean
, true
or false
, if this given Date
is a particular day of the week.