Lai Yu-Hsuan
Lai Yu-Hsuan

Reputation: 28071

Any reason to use Date?

There are at least three types which represent time: Time, Date and DateTime(from ActiveSupport).

My problem is, could DateTime totally replace Date? In other words, if I can use DateTime, is there any reason to use Date instead?

Upvotes: 2

Views: 64

Answers (3)

0x4a6f4672
0x4a6f4672

Reputation: 28245

If you want to store only the date, for example a birthday, or a certain day where an event takes place, then it can be easier to use only date. Then you have no troubles which arise from different time zones and time zone calculations. If you use DateTime, then if you add an offset of -2 hours to 00:00 am, you get 10:00 pm of the previous day.

Upvotes: 1

steenslag
steenslag

Reputation: 80065

require 'date'
d = Date.today
dt = DateTime.now
p Date.public_methods - DateTime.public_methods
#=>[:today]
p DateTime.public_methods - Date.public_methods
#=>[:now]
p d.public_methods - dt.public_methods
#=>[]
p dt.public_methods - d.public_methods
#=>[:hour, :min, :minute, :sec, :second, :sec_fraction, :second_fraction, :offset, :zone, :new_offset]

DateTime is a subclass of Date. Using DateTime, you lose the today Class method and get now in return. You don't lose instance methods.

Upvotes: 1

ksol
ksol

Reputation: 12235

Date does not store any information about the time, neither with the timezone. So you might get into trouble if at some point you'll need to use time data.

Cf this link, which I found clear about what classes should be used, when, and how.

Upvotes: 0

Related Questions