0

What is a clean way to confirm if a string datetime is in the proper format in ruby 3? example input is:

datetime = "2020-02-25T02:57:08.264Z"

I looked through the Time class and couldnt find any built in way, so wondering if I may have overlooked something.

Ankit
  • 6,772
  • 11
  • 48
  • 84
srisha mo
  • 9
  • 2
  • To validate a string, you'd typically use a regular expression. See [Validate ISO 8601 Dates and Times](https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch04s07.html) for various examples. – Stefan Aug 29 '22 at 09:43
  • 1
    Define what you mean by **proper** format. Proper for what? – user1934428 Aug 29 '22 at 10:15

1 Answers1

1

You can try to parse the datetime string and see if it raises an error. Here is one version, which tries to parse the standard ISO8601 format string. If there is an exception it would return false; otherwise return true.

def valid_time?(datetime)
  Time.parse(datetime)
  true
rescue
  false
end

valid_time?("2020-02-25T02:57:08.264Z") # returns true
valid_time?("asdasd") # returns false

If the time string is in a different format and you know the format beforehand, then you can try the same pattern with strptime

def valid_time?(time_string, format)
  Time.strptime(time_string, format)
  true
rescue
  false
end

valid_time?("12/32/2020", "%M/%d/%Y") # returns false
valid_time?("12/23/2020", "%M/%d/%Y") # returns true
Ankit
  • 6,772
  • 11
  • 48
  • 84
  • `Time.parse` attempts to parse various time formats. For ISO 8601 there's a dedicated method [`Time.iso8601`](https://ruby-doc.org/stdlib-3.1.2/libdoc/time/rdoc/Time.html#iso8601-method) – Stefan Aug 29 '22 at 07:15
  • Never use `Time.parse` to validate timestamps. It tries very hard to accept many partial formats so that e.g. `"3:25"` is accepted by `Time.parse` but very likely is not valid according to OP's rules. Either use `Time.iso8601` or `Time.strptime` or even just a Regex. – Holger Just Aug 29 '22 at 13:00