Any easy way to check if a variable / object is of Date
/ Time
/ DateTime
type? Without naming all the types
9 Answers
Another option:
def is_datetime(d)
d.methods.include? :strftime
end
Or alternatively:
if d.respond_to?(:strftime)
# d is a Date or DateTime object
end
-
14Thanks for this answer. It led me to this solution :
d.respond_to?(:strftime)
– StéphaneNov 28, 2017 at 13:20
you can inspect the class of a object doing
object.class
It should return Date, String or whatever it is. You can also do the reverse and check if an object is an instance of a class:
object.instance_of?(class)
where class is the one you want to check (String, Date), returning true/false
If you want to verify the object, here you have a couple of examples:
nisevi@nisevi ~:$ irb
irb(main):001:0> require "date"
=> true
irb(main):002:0> require "time"
=> true
irb(main):003:0> d = Date.new
=> #<Date: -4712-01-01 ((0j,0s,0n),+0s,2299161j)>
irb(main):004:0> dt = DateTime.new
=> #<DateTime: -4712-01-01T00:00:00+00:00 ((0j,0s,0n),+0s,2299161j)>
irb(main):005:0> t = Time.new
=> 2016-06-22 21:33:09 +0200
irb(main):014:0> d.instance_of?(Date)
=> true
irb(main):015:0> d.instance_of?(DateTime)
=> false
irb(main):016:0> d.instance_of?(Time)
=> false
irb(main):017:0> dt.instance_of?(DateTime)
=> true
irb(main):018:0> dt.instance_of?(Time)
=> false
irb(main):019:0> dt.instance_of?(Date)
=> false
irb(main):020:0> t.instance_of?(Time)
=> true
irb(main):021:0> t.instance_of?(DateTime)
=> false
irb(main):022:0> t.instance_of?(Date)
=> false
Also I think that TimeZone is from Rails and not from Ruby.
As per your comment if you want to convert a Time object to DateTime I think that something like this it should work:
def time_to_datetime time
return time.to_datetime if time.instance_of?(Time)
false
end
Here you have some code:
irb(main):026:0> t.instance_of?(Time)
=> true
irb(main):027:0> t.methods.sort.to_s
=> "[:!, :!=, :!~, :+, :-, :<, :<=, :<=>, :==, :===, :=~, :>, :>=, :__id__, :__send__, :asctime, :between?, :class, :clone, :ctime, :day, :define_singleton_method, :display, :dst?, :dup, :enum_for, :eql?, :equal?, :extend, :freeze, :friday?, :frozen?, :getgm, :getlocal, :getutc, :gmt?, :gmt_offset, :gmtime, :gmtoff, :hash, :hour, :httpdate, :inspect, :instance_eval, :instance_exec, :instance_of?, :instance_variable_defined?, :instance_variable_get, :instance_variable_set, :instance_variables, :is_a?, :isdst, :iso8601, :itself, :kind_of?, :localtime, :mday, :method, :methods, :min, :mon, :monday?, :month, :nil?, :nsec, :object_id, :private_methods, :protected_methods, :public_method, :public_methods, :public_send, :remove_instance_variable, :respond_to?, :rfc2822, :rfc822, :round, :saturday?, :sec, :send, :singleton_class, :singleton_method, :singleton_methods, :strftime, :subsec, :succ, :sunday?, :taint, :tainted?, :tap, :thursday?, :to_a, :to_date, :to_datetime, :to_enum, :to_f, :to_i, :to_r, :to_s, :to_time, :trust, :tuesday?, :tv_nsec, :tv_sec, :tv_usec, :untaint, :untrust, :untrusted?, :usec, :utc, :utc?, :utc_offset, :wday, :wednesday?, :xmlschema, :yday, :year, :zone]"
irb(main):028:0> t.to_datetime
=> #<DateTime: 2016-06-22T21:33:09+02:00 ((2457562j,70389s,767750206n),+7200s,2299161j)>
irb(main):029:0> t.instance_of?(Time)
=> true
irb(main):030:0> t.instance_of?(DateTime)
=> false
irb(main):031:0> tdt = t.to_datetime
=> #<DateTime: 2016-06-22T21:33:09+02:00 ((2457562j,70389s,767750206n),+7200s,2299161j)>
irb(main):032:0> tdt.instance_of?(Time)
=> false
irb(main):033:0> tdt.instance_of?(DateTime)
=> true
Here you have some interesting info In Ruby on Rails, what's the difference between DateTime, Timestamp, Time and Date?
In rails 5.2+
you can test if an object is_a?
Date.today.is_a?(Date) # -> true
Date.today.is_a?(DateTime) # -> false
I do not think there is an "easy way" without typing all the type variations of Date
/ Time
/ DateTime
/ Timezone
out.
The simplest and fastest way is to do dateTime.is_a?(DateTime)
or Time.is_a?(Time)
, repeat ad nausem - which all will return a boolean.
Conversely you can also use kind_of?.
You might also be able to find a framework that has a function to check all of the variations of date and time.
To find what class the module (or method) is located in, you use the .class
function, this allows you to inspect Ruby objects to find out what class they are located in. The syntax for this looks like this: object.class
. Here's some examples:
irb(main):001:0> require 'date'
=> true
irb(main):002:0> d = Date.today
=> #<Date: 2016-06-22 ((2457562j,0s,0n),+0s,2299161j)>
irb(main):003:0> t = Time.now
=> 2016-06-22 18:52:24 -0500
irb(main):004:0> t.class
=> Time
irb(main):005:0> d.class
=> Date
As you can see this is an easy and simple way to find the class that the object is in.
The Column objects returned by columns and columns_hash can then be used to get information such as the data type and default values, for example:
User.columns_hash['email'].type
=> :string
User.columns_hash['email'].default
=> nil
User.columns_hash['email'].sql_type
=> "varchar(255)"
(Source)
In Rails you can use the acts_like?
method. Time does not act_like_date?
so you need to check for date and time.
var.acts_like?(:date) || var.acts_like?(:time)
For the sake of completion, another option would be:
def responds_to_datetime?(date)
true if date.to_datetime rescue false
end
.map
to convert each attribute that is Time to datetime. Would be great that in the future the type of time could be changed in the DB, hence the question.. but I guess I'm just kinda curious now...forum
. instance_of?
or.class
is probably the best solution to finding the class of an object in Ruby. GL with your work!