2

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

Amit Patel
  • 15,609
  • 18
  • 68
  • 106

3 Answers3

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

will replace both positive and negative offsets. But why?

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • My application receives date/time in user's timezone. At some points in the application I want to consider the time as if it is in UTC. So before giving `params[:date]` I replace it's TZ part in `before_filter` so rest is taken care by AR – Amit Patel Apr 17 '12 at 19:58
1

How about simple:

str = "2012-04-17T15:40+05:30"
str.sub!(/.{6}\z/, '+00:00') # => "2012-04-17T15:40+00:00"
jdoe
  • 15,665
  • 2
  • 46
  • 48
  • It also worked but above two looks more cleaner. Thanks for sharing, @jdoe. – Amit Patel Apr 17 '12 at 20:03
  • `/.{6}\z/` -- is something may be cleaner? :) – jdoe Apr 17 '12 at 20:05
  • I just payed attention in mu answer to your exclamation mark `!` at the end of the sub/gsub. With this mark the function replaces the content of the string it applied to. So it's more logical to use it not for literal but for variable. I guess you got the idea. – jdoe Apr 18 '12 at 05:15
  • I have used literal so it is more readable here but I have variable which is being manipulated. – Amit Patel Apr 18 '12 at 07:10
1

Change your regex to

/(\+|\-)\d\d:\d\d/
David Gorsline
  • 4,933
  • 12
  • 31
  • 36