Skip to content

Instantly share code, notes, and snippets.

@mwlang
Created June 17, 2015 13:58
Show Gist options
  • Save mwlang/f4b0bbcb48269da1b6f4 to your computer and use it in GitHub Desktop.
Save mwlang/f4b0bbcb48269da1b6f4 to your computer and use it in GitHub Desktop.
normalizes a date/timestamp to be timezone of the system it's coming from. input can be Time, DateTime, Date, or String -- we don't know what we'll get, so handle all of these.
require 'rails_helper'
RSpec.describe Soap::Methods::InstanceMethods do
describe "normalize_timestamp" do
class Foo
include Soap::Methods
end
def et value
Foo.new({}, "").normalize_timestamp value
end
it "returns a given Time" do
time = Time.new(2015, 6, 3, 16, 47, 14, '+05:00')
expect(et time).to eq time
end
it "returns a given Date" do
date = Date.today
expect(et date).to eq date
end
it "interprets a date string" do
date = Date.civil(2015, 6, 3)
expect(et date.strftime("%Y-%m-%d")).to eq date
end
it "interprets 2015-06-03T16:47:14" do
time = Time.new(2015, 6, 3, 16, 47, 14, '+05:00')
expect(time.strftime("%H:%M:%S")).to eq "16:47:14"
expect(et "2015-06-03T16:47:14").to eq time
expect(et "2015-06-03 16:47:14").to eq time
end
end
end
TIME_REGEXP = /(\d{4})\-(\d{2})\-(\d{2})[\s|T](\d{2})\:(\d{2})\:(\d{2})/
DATE_REGEXP = /(\d{4})\-(\d{2})\-(\d{2})/
SRC_TIME_OFFSET = "+05:00"
def normalize_timestamp ts
return unless ts
case
when ts.is_a?(DateTime)
DateTime.new(ts.year, ts.month, ts.day, ts.hour, ts.min, ts.sec, SRC_TIME_OFFSET)
when ts.is_a?(Time)
Time.new(ts.year, ts.month, ts.day, ts.hour, ts.min, ts.sec, SRC_TIME_OFFSET)
when ts.is_a?(String)
if ts.match(TIME_REGEXP)
return Time.new(*ts.match(TIME_REGEXP).captures.map(&:to_i), SRC_TIME_OFFSET)
end
if ts.match(DATE_REGEXP)
return Date.civil *ts.match(DATE_REGEXP).captures.map(&:to_i)
end
else
return ts
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment