Section 7.20. Retrieving a DateTime Value from a String


7.19. Interconverting Between Time, Date, and DateTime

Ruby has three basic classes dealing with dates and times: Time, Date, and DateTime. The following is a description of each:

  • The Time class is mostly a wrapper for the underlying time functions in the C library. These are typically based on the UNIX epoch and thus cannot represent times before 1970.

  • The Date class was created to address this shortcoming of the Time class. It can easily deal with older dates such as Leonardo da Vinci's birthday (April 15, 1452), and it is intelligent about the dates of calendar reform. But it has its own shortcoming; it can't deal with the time of day that Leonardo was born. It deals strictly with dates.

  • The DateTime class inherits from Date and tries to be the best of both worlds. It can represent dates as well as Date can, and times as well as Time can. This is often the "right" way to represent a date-time value.

    But don't be fooled into thinking that a DateTime is just a Date with an embedded Time. There are, in fact, several methods missing from DateTime, such as usec, dst?, and others.

So we have these three classes. Unfortunately there is no good standard way to convert between them. As Ruby continues to change, some of these details will be ironed out. For now, these methods in Listing 7.2 will suffice. Thanks to Kirk Haines for providing them.

Listing 7.2. Interconverting Between Date and Time Classes

class Time   def to_date     Date.new(year, month, day)   rescue NameError     nil   end   def to_datetime     DateTime.new(year, month, day, hour, min, sec)   rescue NameError     nil   end end class DateTime   def to_time     Time.local(year,month,day,hour,min,sec)   end end class Date   def to_time     Time.local(year,month,day)   end end

Any exceptions will be propagated except NameError. Why do we check for this one? Because it is conceivable that the program doesn't do a require of the date library (remember that Date and DateTime are part of this standard library, not part of the core). In such a case, to_datetime and to_date will both return nil.




The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net