What's the difference between DateTime
and Time
classes in Ruby and what factors would cause me to choose one or the other?
Ruby – Difference between DateTime and Time in Ruby
datetimerubytime
Related Question
- Determine Whether Two Date Ranges Overlap
- Mysql – Should I use the datetime or timestamp data type in MySQL
- Python – How to get the current time in Python
- Python – Converting string into datetime
- Unix – What do ‘real’, ‘user’ and ‘sys’ mean in the output of time(1)
- Javascript – Convert a Unix timestamp to time in JavaScript
- Ruby-on-rails – In Ruby on Rails, what’s the difference between DateTime, Timestamp, Time and Date
Best Solution
Newer versions of Ruby (2.0+) do not really have significant differences between the two classes. Some libraries will use one or the other for historical reasons, but new code does not necessarily need to be concerned. Picking one for consistency is probably best, so try and mesh with what your libraries expect. For example, ActiveRecord prefers DateTime.
In versions prior to Ruby 1.9 and on many systems Time is represented as a 32-bit signed value describing the number of seconds since January 1, 1970 UTC, a thin wrapper around a POSIX-standard
time_t
value, and is bounded:Newer versions of Ruby are able to handle larger values without producing errors.
DateTime is a calendar-based approach where the year, month, day, hour, minute and second are stored individually. This is a Ruby on Rails construct that serves as a wrapper around SQL-standard DATETIME fields. These contain arbitrary dates and can represent nearly any point in time as the range of expression is typically very large.
So it's reassuring that DateTime can handle blog posts from Aristotle.
When choosing one, the differences are somewhat subjective now. Historically DateTime has provided better options for manipulating it in a calendar fashion, but many of these methods have been ported over to Time as well, at least within the Rails environment.