Date and Time Flashcards
What is the difference between Date and DateTime classes?
The Date class has no concept of minutes, seconds or hours. This class stores everything internally in terms of days.
The DateTime class is a subclass of Date and it can store seconds in addition to dates.
What is the use of Time class?
You can use the Time class in Ruby to represent a time & date.
What are the classes available for Date and Time in Ruby?
Date,Time,DateTime
In which format Time class stores the information?
This date has three components:
day
month
year
And time:
hours
minutes
seconds
This information is stored by the Time class as the number of seconds since the Epoch, also known as Unix time.
Which one is True?
You can get an object that represents the current time using Time.now
You can create a Time object using an Unix timestamp & the at method
You can give the starting date in numbers to Time.new (format: year/month/day)
All are true
Time.new()
Time.at(628232400) #=> 1989-11-28 00:00:00 -0500
Time.new(1993, 02, 24, 12, 0, 0, “+09:00”)
What is the use of ‘strftime’ method?
This method is strftime, which basically means ‘format time’.
It works by passing a string with format specifiers, these specifiers will be replaced by a value.
time = Time.new
time.strftime(“%d/%m/%Y”)
Explain the following in strftime method?
%M %S %I %A %B
It gives
%M Minutes %S Seconds (00..60) %I Hour (1..12) %A Day of the week (name) %B Month (name)
Consider the error. How to fix it?
irb(main):001:0> Date.today Traceback (most recent call last): 2: from /Library/Ruby/Gems/2.6.0/gems/irb-1.0.0/exe/irb:11:in `' 1: from (irb):1 NameError (uninitialized constant Date) Did you mean? Data
To use the Date class you need to require ‘date’.
You can get the current date using Date.today.
irb>Date.today
How to convert a string like ‘2018-01-01 00:00’ into a Time object?
using parse method
require ‘time’
Time.parse(“September 20 18:00”)
How to get all the month names and Week days names from Date class?
The Date class has some constants.
For example, there is an array with the months of the year and another with the days of the week.
require ‘date’
puts Date::MONTHNAMES #all months
puts Date::DAYNAMES #all days
Difference between Time and DateTime class?
Both Time and DateTime can get the same job done, with the main difference being that Time is implemented in C, so it will be faster.
> 3.days.ago
Is this valid method in Ruby? If not,
How we can get this output?
These methods are not available in pure Ruby,
they are added by the ActiveSupport component of Rails.
- day # ActiveSupport::Duration
- days.ago # ActiveSupport::TimeWithZone