How to match the clockwise format YYYY-MM-DDThh: mm: ssTZD in ruby

I would like to check the iso8601 format for the date entered in ruby, for example, start_date = "2011/05/05" should be compared for the format 2011-05-05T00: 00: 00-04: 00 , and errors are returned accordingly. Should we use regex here or is there any method present for this?

+6
source share
2 answers

It looks like you want Time.iso8601 :

 require 'time' iso = Time.iso8601(start_date) 

See this blog post for more details.

EDIT: here's a short but complete test program that works:

 require 'time' text = "2011-05-05T00:00:00-04:00" parsed = Time.iso8601(text) puts parsed 

Conclusion:

 Thu May 05 04:00:00 UTC 2011 
+8
source

To check for regular expressions (with extra microseconds and a time zone), use:

 ^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[0-1]|0[1-9]|[1-2][0-9])T(2[0-3]|[0-1][0-9]):([0-5][0-9]):([0-5][0-9])(\.[0-9]+)?(Z|[+-](?:2[0-3]|[0-1][0-9]):[0-5][0-9])?$ 

Test for: http://rubular.com/r/qFFrhzvdsS

Not recommended in scenarios when performance matters !

+3
source

Source: https://habr.com/ru/post/906292/


All Articles