In Ruby, Date class is prepared as a class that handles dates, and by using this, it is easy to calculate data that is difficult to calculate accurately with just numbers such as leap year, number of days per month, management of days of the week, etc.
It will be possible to obtain it.
In addition to dates, there are classes that manage time and classes that handle both dates and times.
name of the class | Manageable data |
---|---|
Date class | date |
Time class | time |
DateTime class | Both date and time |
When using the Date class, you need to call the "Date "library on your Ruby code
.
The require method
plays that role, which makes it possible to refer to an external file and get the class defined there.
~~ * In the case of Rails application, the class can be referenced in any file, so the description of require" ~ "
is unnecessary ~~ (corrected below)
** * In the case of Rails application, it is not necessary to describe require "~" because it has a function to automatically read the reference file according to the specifications of the Rails framework **
require "date"
#Date library"date"To capture
:
:
require "date"
today = Date.today
#Create a Date object by automatically calculating today's date
require "date"
today_str = "2020-12-30"
Date.parse(today_str)
#December 30, 2020 Date object created
require "date"
today = Date.new(2020, 12, 30)
#December 30, 2020 Date object created
To get specific information from the Date object created by the above method, use the following code.
require "date"
today = Date.today
today.year #Get the year from the created Date object
today.mon #Get the month from the created Date object
today.mday #Get the date from the created Date object
today.wday #Get the day of the week as a number from the created Date object
I would be grateful if you could point out any mistakes in the description. We are looking forward to hearing from you.
Recommended Posts