Is there any class or lib to deal with Times without Date? (Eg “3:30
PM” - but I don’t want it associated with a date.)
Ideally, I’d like to:
Have clock arithmetic (1 AM minus 90 minutes is 11:30 PM)
Convert from DateTime to dateless times (and, by adding a date, back)
Store it with ActiveRecord
Any ideas?
Have you tried the Time class?
#!/usr/bin/ruby -w
is = Time.new
h = 4 # hours
was = is - (h * 60 * 60)
puts “Time now: #{is}\nTime then: #{was}”
Output:
Time now: Thu Oct 26 14:10:41 PDT 2006
Time then: Thu Oct 26 10:10:41 PDT 2006
The Time object is expressed in seconds elapsed since 1/1/1970 00:00
GMT.
Just add or subtract seconds to get what you want. And the 1970
limitation
isn’t actually much of a limitation:
The problem with Time is that it tracks a date also.
Let me explain:
I have a scheduler, which, for example, can be set to do something at 3
PM. I’d like to store that time in an object, and then take a Time,
chop off the date part, and see if the time matches.
The problem with Time is that it tracks a date also.
Let me explain:
I have a scheduler, which, for example, can be set to do something at 3
PM. I’d like to store that time in an object, and then take a Time,
chop off the date part, and see if the time matches.
puts
puts "superclass of DateTime : #{DateTime.superclass}"
% ruby date-time.rb
date.to_date yields result 2006-10-27 with class of Date
time.to_date yields result 2006-10-27 with class of Date
date_time.to_date yields result 2006-10-27T00:18:27-0600 with class
of DateTime
date.to_time yields result Fri Oct 27 00:00:00 -0600 2006 with
class of Time
time.to_time yields result Fri Oct 27 00:18:27 -0600 2006 with
class of Time
date_time.to_time yields result Fri Oct 27 00:00:00 -0600 2006 with
class of Time
superclass of DateTime : Date
When to_date is called on an instance of DateTime its still calling it
on Date object since DateTime.superclass == Date. So anywhere a Date is
used, a DateTime can be used.
enjoy,
-jeremy
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.