Ruby checks if datetime is iso8601 and saves

I need to check if DateTime is in valid ISO8601 format. For example:#iso8601?

I checked if ruby ​​has a specific method, but I couldn't find it. I am currently using date.iso8601 == date

to test 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, so I need the iso8601 string format. And I thought it was better or correct, store the date in the database in the correct format or let ActiveRecord do its job and manipulate it only when I need time information.

+3


source to share


1 answer


I don't quite understand your question. I assume you want to check the DateTime string if it is a valid ISO8601 date string or not. Correct me if I am wrong.

You can use class methods Time.iso8601

and Date.iso8601

. To use them, you need the "date" and "time" library from the standard library. One of the caveats, as you can see from the name, they are not a predicate method (without?), Instead they raise an ArgumentError message with an "invalid date" message if an invalid string is entered. So, you need to add an initial crash 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 detailed than your date date.iso8601 ==. But I am posting it because I don't understand how your method works. It date.iso8601 == date

would always be false for me . I am wrong?

UPDATE

As an answer to your updated question, your best bet is to simply store the DateTime, usually in the database, and call the method iso8601

to get the ISO8601 string. To create a DateTime, you can simply use Time.iso8601 to parse the input string into a DateTime object.

+4


source







All Articles