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