[Ruby] Date, Time, Datetime class basics

--Can handle date and time. Datetime manages both, Date manages the date, and Time manages the time. ――It is possible to manage leap years, the number of days per month, days of the week, etc. --There are also convenient methods unique to Rails. More readable and safer.

Date class

--A class that handles dates. --Requires require" date ".

Example)How to use the Date class

require "date"   #Required because it refers to an external file and gets the class

#today method
  today = Date.today           #today
  today - 1                    #yesterday
  today.year                   #Year
  today.mon                    #Month
  today.mday                   #Day
  today.wday                   #Day of the week
  today.strftime('%a')         # "Sat"

#Does the date exist?
Date.valid_date?(2020, 9, 5)   # true
Date.valid_date?(2020, 9, 31)  # false
Date::exist?(2001, 1, 31)      # 2451941(Julian day returns)
Date::exist?(2001, 1, 32)      # false

# Date::new1 method(Julian day)
  #Julian day:January 1, 4713 BC(Julian calendar)noon(Greenwich Mean Time)Elapsed days when the calendar is based on
julius = Date::exist?(2001, 1, 31) #Number of days elapsed(2451941)
Date::new1(julius).to_s      # "2001-01-31"

# eap?Method(Leap year? )
Date.new(2000).leap?   # true
Date.new(2001).leap?   # false

#parse method
date = Date.parse("2020-09-05")  #Create Date object based on arguments
Date.parse(str_time).to_time     #Convert from Date type to Time type(* The time is 00:00:Become 00)

#new method(Used to instantiate a class)
  input = Date.new(2020, 9, 5)   #Create Date object based on arguments
  input += 10                    #Get 10 days later
  input - date                   # 10
  Date.new(2020, 9, -1)          #If the third argument is negative, counting from the last day(※ -1 is the last day)。

Time class (date and time)

--Class that handles date and time in UNIX time --Requires require" time "

Example)How to use the Time class

require "time"

now = Time.current               #Current time
Time.mktime(2000, 1, 1).yday     # 2000/1/Days from 1
Time.parse(str_time).to_date     #Convert from Time type to Date type

today = Time.now()               #Current time( 2020-06-17 19:30:02 +0000 )
  today.year                     #Year(2020)
  today.month                    #Month(6)
  today.day                      #Day(17)

  now.yesterday                #yesterday
  now.tomorrow                 #next day
  now.ago(3.days)              #● days ago
  now.since(3.days)            #● days later

  now.beginning_of_week        #First of the week
  now.end_of_week              #End of this week
  now.prev_week(:monday)       #Last monday
  now.next_week(:monday)       #Next Monday

  now.prev_month               #last month
  now.next_month               #Next month
  now.ago(3.month)             #● months ago
  now.since(3.month)           #● months later
  now.beginning_of_month       #Beginning of the month
  now.end_of_month             #End of month

  now.prev_year                #Previous year
  now.next_year                #following year
  now.ago(3.years)             #● years ago
  now.since(3.years)           #● Years later

#parse method
Time.parse("2020-09-05 12:22:50")
Time.parse("2020/09/05 12:22:50")
Time.parse("2020-09/05 12:22:50")
Time.parse("20200905 122250")
Time.parse("2020/09/05 12")         # 2020-09-05 12:00:00 +0900
Time.parse("2020/09/05 12:22")      # 2020-09-05 12:22:00 +0900
  #Can be changed
  Time.parse("2020.06.17 12:00:00") do |year|
    if year < 100
      if year >= 69
        year + 1900
        year + 2000

#gm method, utc method(Coordinated Universal Time)
Time.gm(2001, 5, 20, 23, 59, 59)    # Sun May 20 23:59:59 UTC 2001
#local method, mktime method(Local time)
Time.local(2001, 5, 20, 23, 59, 59) # Sun May 20 23:59:59 JST 2001

#String(14 digits)Conversion to
now.to_s                        # '20200905122250'
now.insert(8, ' ')              # '20200905 122250' (Insert a space in the 8th digit)

DateTime class

--A class that handles dates and times (subclass of Date). --You can use the same method as the Date class. Can handle up to the time. --Requires require" date ".

Example)How to use the DateTime class

require "date"

date = DateTime.now    #Current date and time(2020-09-05 17:08:37 +0900)
DateTime.now - 1       #yesterday

input = DateTime.new(2020, 9, 5, 17, 8, 37)
date = DateTime.parse('2020-09-05T17:08:37')
  date += 10
  date - input                 # 10
  date.year                    # 2020
  date.strftime('%a')          # "Sat"
  date.strftime("%Y year%m month%d day") #September 5, 2020

strftime method

--Specify acquisition / display format.

Notation meaning Example
%A Day of the week Sunday,Monday,..
%a Day of the week(Abbreviated name) Sun,Mon,..
%B Month January,February,..
%b Month(Abbreviated name) Jan, Feb,..
%c Date and time
%d Day 01-31
%H time(24h) 00-23
%I time(12h) 01-12
%j Total date of the year 001-366
%M Minutes 00-59
%m Month(Numbers) 01-12
%p AM or PM AM,PM
%S Seconds 00-60(※60はうるうSeconds)
%U week(Numbers)* Starts on Sunday 00-53
%W week(Numbers)* Starts on Monday 00-53
%w Day of the week(Numbers)※日Day of the weekが0 0-6
%X Times of Day 09
%x date 09/20/20
%Y Year 2020
%y Year(Last 2 digits) 00-99
%Z Time zone JST
%% Percentage character

Recommended Posts

[Ruby] Date, Time, Datetime class basics
Ruby basics
Ruby basics
Explanation of Ruby Time and Date objects
Class in Ruby
Basics of Ruby
[Ruby] Summary of class definitions. Master the basics.
About date / time type of Doma2 entity class
Use of Date class
[Java] Date / time operations
[Ruby] Exception handling basics
[Rails] Precautions when comparing date and time with DateTime
Ruby on Rails basics
[Ruby] Class nesting, inheritance, and the basics of self
Handling of date and time in Ruby. Use Date and Time properly.
What is the LocalDateTime class? [Java beginner] -Date and time class-
[Ruby] Display today's day of the week using Date class
[GCD] Basics of DispatchQueue class
Write class inheritance in Ruby
[Self-use memo] (Ruby) class, class instance, instance
What are Ruby class methods?
[Ruby] Class methods, instance methods, etc.
[Java basics] What is Class?
Which class should I use to get the date and time in my Rails app (Time, DateTime, TimeWithZone)