Skip to content

Instantly share code, notes, and snippets.

@shuhei
Last active August 29, 2015 14:16
Show Gist options
  • Save shuhei/041aecdd4bff2872c5ca to your computer and use it in GitHub Desktop.
Save shuhei/041aecdd4bff2872c5ca to your computer and use it in GitHub Desktop.
String assignment to date attribute taking account of timezone

Sometimes we want to handle date as Date in JavaScript and JavaScript's JSON.parse converts Date to an string in UTC ISO 8601 format.

JSON.stringify({ date: new Date(2015, 2, 14) })
// "{"date":"2015-03-13T15:00:00.000Z"}"

ActiveRecord's date attribute doesn't take timezone into account when it converts string to date.

class Application < Rails::Application
  config.time_zone = 'Tokyo'
end

class Person < ActiveRecord::Base
  # birth_date :date
end

expect(Person.new(birth_date: '2015-02-13T15:00:00.000Z').birth_date)
  .to eq(Date.new(2015, 2, 13))

StringDateAssignmentWithTimezone concern overrides date attribute mutators in your ActiveRecord model to take timezone into account.

class Person < ActiveRecord::Base
  include StringDateAssignmentWithTimezone
end

expect(Person.new(birth_date: '2015-02-13T15:00:00.000Z').birth_date)
  .to eq(Date.new(2015, 2, 14))
module StringDateAssignmentWithTimezone
extend ActiveSupport::Concern
included do
columns_hash.each do |name, col|
next unless col.type == :date
define_method("#{name}=") do |value|
time = value.is_a?(String) ? Time.zone.parse(value) : value
self[name] = time
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment