Domanda

I've looked through a lot of issues like this but none seem to correspond to my issue, which is:

I have a Rails app that contains events. Event is a model that has attributes for start date (Date field), start time (Time) and end time (Time). When I created them, I didn't convert any of the entered dates to UTC based times (all times local).

I'm trying to find out if the event is over. I've added a few methods to my model that should help with this, but because I'm comparing Apples (non-UTC) to Oranges (UTC) time. I'm running into a brick wall.

Because I'm mixing Date and Times, I've added the following methods to my Event model:

helpers

  def date_start_time
    return DateTime.new(self.date.year, self.date.month, self.date.day, self.start_time.hour, self.start_time.min, self.start_time.sec)
  end
  def date_end_time
    return DateTime.new(self.date.year, self.date.month, self.date.day, self.end_time.hour, self.end_time.min, self.end_time.sec)
  end

in_past method

  def in_past
    logger.debug 'comparing end time: ' + self.date_end_time.to_s +  ' to the current time: ' + DateTime.now.to_s
    self.date_end_time <= DateTime.now
  end

I'm loading an event in Rails Console that should end in a few minutes, but I'm getting a true to in_past:

1.9.3-p194 :020 > event.in_past
comparing end time: 2013-08-19T20:38:00+00:00 to the current time: 2013-08-19T20:37:22-05:00
 => true 

I've tried adding .zone to my DateTime.now, but that makes it worse it seems. I feel like I've tried every combination of Zone options here and really I'd just prefer to ignore time zones since all events are currently local.

Thoughts? Suggestions?

È stato utile?

Soluzione

The quick solution to this is add timezone to rails config (application.rb) like this

config.time_zone = '<your local timezone>'

You can get all the available timezones by

#rake time:zones:all
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top