tentimes
tentimes

Reputation: 1462

Changing ISO8601 formatted datetime into Rails datetime object

I am using a jquery plugin called Fullcalendar (v2.02) which provides datetime objects as ISO8601.

I can easily change a datetime object into iso8601 by just using date_object.iso8601 (a simple ruby method).

The problem I am having is when Fullcalendar gives me a datetime range of, say, start=1401058800 and end=1404687600 (my June Calendar) I then need to get these start and end times in date format so that I can query my meetings table to return any meeting instances that occur during this time.

In Rails 4.1.1 the following function worked fine:

def self.format_date(date_time)
    date_time.to_datetime
end

But in Rails 4.1.2 it return an error (when trying to convert the start or end iso8601 times):

ArgumentError - invalid date

Does anyone know please how I can convert (in Rails 4.1.2) an iso8601 datetime object into a datetime object I can query my database with?

The meeting table format is as follows:

# == Schema Information
#
# Table name: meetings
#
#  id          :integer          not null, primary key
#  title       :string(255)
#  starts_at   :datetime
#  created_at  :datetime
#  updated_at  :datetime
#  description :string(255)
#  ends_at     :datetime
#  user_id     :integer
#  all_day     :boolean

The scope is:

scope :between, ->(start_time, end_time, user_id) {
       where(starts_at: (Meeting.format_date(start_time)..Meeting.format_date(end_time)),
             user_id: user_id)
  }

Upvotes: 0

Views: 582

Answers (1)

Ruby Racer
Ruby Racer

Reputation: 5740

Try these:

Time.at(1401058800).to_datetime
Time.at(1401058800).to_date

Or, to be precise:

def self.format_date(date_time)
    Time.at(date_time.to_i).to_datetime
end

Upvotes: 1

Related Questions