Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to replace timezone offset

I have a string representing date/time with timezone. I want to change the timezone part to UTC that is +00:00

Please help me to write regext to match +05:30, -03:30 etc and replace it with +00:00

I tried with "2012-04-17T15:40+05:30".gsub!(/\+\d\d:\d\d/, '+00:00') which gives me expected results but I don't know how to match -5:30

I would appreciate if someone helps me to write regex which work with both 2012-04-17T15:40+05:30 and 2012-04-17T15:40-05:30

Thanks, Amit Patel

like image 931
Amit Patel Avatar asked Jun 12 '26 04:06

Amit Patel


2 Answers

"2012-04-17T15:40+05:30".gsub!(/[+-]\d\d:\d\d/, '+00:00')

will replace both positive and negative offsets. But why?

like image 107
Tim Pietzcker Avatar answered Jun 14 '26 19:06

Tim Pietzcker


How about simple:

str = "2012-04-17T15:40+05:30"
str.sub!(/.{6}\z/, '+00:00') # => "2012-04-17T15:40+00:00"
like image 43
jdoe Avatar answered Jun 14 '26 18:06

jdoe