I have a rails app with events. My event table has a field called start_date
which is of datetime type. Currently when i save an event using chronic to parse the start_date field, the date gets incorrectly stored (or at least returns incorrectly).
Example: I saved an event and in the textfield for start_date i entered 9/14/13 at 9am
. It saved the data, refreshed the page, and the value in the textfield was 9/14/13 at 11am
. The value in the mysql table is 2013-09-14 16:00:00
.
What is going on here? This only happens on my server and not when running locally.
application.rb:
config.time_zone = 'Central Time (US & Canada)'
models/event.rb:
class Event < ActiveRecord::Base
belongs_to :user
attr_accessible :description, :name, :start_date_string
validate :name_not_blank
validate :start_date_not_blank
# Validate that the name is not blank
def name_not_blank
errors.add(:name, "Name can't be blank") unless !name.blank?
end
# Validate that the name is not blank
def start_date_not_blank
errors.add(:start_date, "Date and Time can't be blank") unless !start_date.blank?
end
# getter
def start_date_string
@start_date_string || start_date.in_time_zone.try(:strftime, "%m/%d/%Y at %I:%M %P")
end
# setter
def start_date_string=(value)
@start_date_string = value
self.start_date = parse_start_date
end
# parse the start_date
def parse_start_date
Chronic.parse(start_date_string)
end
end
helpers/application_helper.rb:
# Formats a date to words (i.e. March 20, 1980 at 10:00 am)
def spell_date_and_time(date)
date.strftime("%B %d, %Y at %I:%M %P")
end
edit.html.erb
<span class="timestamp"><%= spell_date_and_time(event.start_date) %></span>