Ruby check if datetime is a iso8601 and saving
I need to check if a DateTime is in a valid ISO8601 format.
Like: #iso8601?
I checked if ruby has a specific method but I haven't found any.
Currently I'm using date.iso8601 == date
to check this.
Is there a good way to do this?
EDIT
Explaining my environment, and changing the scope of the question.
So, my project will use the js api FullCalendar, that's why i need a iso8601 string format. And I wondered what it's better or the correct way, save the date in the database in the correct format, or let the ActiveRecord do their job and manipulate it on just when I require the time information.
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.