I dont' quite understand your question. I am assuming that you want to check a DateTime string if it's a valid ISO8601 format date string or not. Correct me if I am wrong.
You can use the class methods Time.iso8601
and Date.iso8601
. In order to use them, you need to require the 'date' and 'time' library from standard library. One caveat is, as you can see from the name, they are not predicate method (without ?), instead they raise an ArgumentError with "invalid date" message if the wrong string is being input. So, you need to add a begin rescue block. eg.
require 'time'
t = Time.now
time_string = t.rfc2822 # intentionally set to wrong format string
begin
Time.iso8601(time_string)
puts "Yeah, correct string"
rescue ArgumentError => e
puts e
puts "Nah, wrong string"
end
This is more verbose than your "date.iso8601 == date". But I am posting it because don't understand how your method works. To me date.iso8601 == date
would always be false. Am I wrong?
UPDATE
As an answer for your updated question, it's best you can just store the DateTime normally in the database and call iso8601
method to get the ISO8601 string. For creating DateTime, you can just use Time.iso8601 to parse the input string into DateTime object.