Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 608
Victor Santos Avatar asked Jul 25 '15 14:07

Victor Santos


People also ask

What time zone is ISO 8601?

Universal Coordinate Time is the time at the zero meridian, near Greenwich, England. UTC is a datetime value that uses the ISO 8601 basic form yyyymmddT hhmmss+|– hhmm or the ISO 8601 extended form yyyy-mm-ddT hh:mm:ss+|– hh:mm.

How do I convert datetime to ISO 8601?

toISOString() method is used to convert the given date object's contents into a string in ISO format (ISO 8601) i.e, in the form of (YYYY-MM-DDTHH:mm:ss. sssZ or ±YYYYYY-MM-DDTHH:mm:ss.

What is a valid ISO 8601 date?

ISO 8601 represents date and time by starting with the year, followed by the month, the day, the hour, the minutes, seconds and milliseconds. For example, 2020-07-10 15:00:00.000, represents the 10th of July 2020 at 3 p.m. (in local time as there is no time zone offset specified—more on that below).


1 Answers

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.

like image 196
dreamingblackcat Avatar answered Nov 13 '22 12:11

dreamingblackcat