7.2. Working with Specific Times (Post-epoch)
Most software only needs to work with dates in the future or in the recent past. For these circumstances, the Time class is adequate. The relevant class methods are mktime, local, gm, and utc.
The mktime method creates a new Time object based on the parameters passed to it. These time units are given in reverse from longest to shortest: year, month, day, hours, minutes, seconds, microseconds. All but the year are optional; they default to the lowest possible value. The microseconds may be ignored on many architectures. The hours must be between 0 and 23 (that is, a 24-hour clock).
t1 = Time.mktime(2001) # January 1, 2001 at 0:00:00 t2 = Time.mktime(2001,3) t3 = Time.mktime(2001,3,15) t4 = Time.mktime(2001,3,15,21) t5 = Time.mktime(2001,3,15,21,30) t6 = Time.mktime(2001,3,15,21,30,15) # March 15, 2001 9:30:15 pm
Note that mktime assumes the local time zone. In fact, Time.local is a synonym for it.
t7 = Time.local(2001,3,15,21,30,15) # March 15, 2001 9:30:15 pm
The Time.gm method is basically the same, except that it assumes GMT (or UTC). Because the authors are in the U.S. Central time zone, we would see an eight-hour difference here:
t8 = Time.gm(2001,3,15,21,30,15) # March 15, 2001 9:30:15 pm # This is only 1:30:15 pm in Central time!
The Time.utc method is a synonym:
t9 = Time.utc(2001,3,15,21,30,15) # March 15, 2001 9:30:15 pm # Again, 1:30:15 pm Central time.
There is one more important item to note. All these methods can take an alternate set of parameters. The instance method to_a (which converts a time to an array of relevant values) returns a set of values in this order: seconds, minutes, hours, day, month, year, day of week (0..6), day of year (1..366), daylight saving (true or false), and time zone (as a string).
Thus these are also valid calls:
t0 = Time.local(0,15,3,20,11,1979,2,324,false,"GMT-8:00") t1 = Time.gm(*Time.now.to_a)
However, in the first example, do not fall into the trap of thinking that you can change the computable parameters such as the day of the week (in this case, 2 meaning Tuesday). A change like this simply contradicts the way our calendar works, and it will have no effect on the time object created. November 20, 1979, was a Tuesday regardless of how we might write our code.
Finally, note that there are obviously many ways to attempt coding incorrect times, such as a thirteenth month or a 35th day of the month. In cases like these an ArgumentError will be raised.