Skip to content

Instantly share code, notes, and snippets.

@funny-falcon
Created March 17, 2011 08:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save funny-falcon/874002 to your computer and use it in GitHub Desktop.
Save funny-falcon/874002 to your computer and use it in GitHub Desktop.
Fast parsing of db timestamp (useful for postgresql and sqlite3 adapters with sequel )
class Time
class << self
def relaxed_rfc3339(date)
if /\A\s*
(-?\d+)-(\d\d)-(\d\d)
[T ]
(\d\d):(\d\d):(\d\d)
(?:\.(\d+))?
(Z|[+-]\d\d(?::?\d\d)?)?
\s*\z/ix =~ date
year = $1.to_i
mon = $2.to_i
day = $3.to_i
hour = $4.to_i
min = $5.to_i
sec = $6.to_i
usec = $7 ? "#{$7}000000"[0,6].to_i : 0
if $8
zone = $8
if zone == 'Z'
offset = 0
elsif zone =~ /^([+-])(\d\d):?(\d\d)?$/
offset = ($1 == '+' ? 1 : -1) * ($2.to_i * 3600 + ($3 || 0).to_i * 60)
end
year, mon, day, hour, min, sec =
apply_offset(year, mon, day, hour, min, sec, offset)
t = self.utc(year, mon, day, hour, min, sec, usec)
t.localtime unless zone =~ /Z|-00:?(00)?/
t
else
self.local(year, mon, day, hour, min, sec, usec)
end
end
end
alias parse_heavy parse
def parse(date)
relaxed_rfc3339(date) || parse_heavy(date)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment