Saghir A. Khatri
Saghir A. Khatri

Reputation: 3128

Comparing dates in ruby on rails

i am stuck in weird issue while comparing dates in ruby on rails.

here is what i am trying to do. i have parsed a file and selected a date into a variable @timeinFile. i am comparing this value to created_at of my User. here is the code:

@date=User.last.created_at
@arr.each do |i| 
    j=i.partition('(')[2]  
    @timeinFile=j.partition(')')[0].to_datetime
    if @date < @timeinFile    #Error: undefined method `to_datetime' for nil:NilClass
            @val='true'
    end
end

when i Comment if statement and paste values individually i get the following output

<p> <%= @date %> </p> ----------> 2013-08-05 09:16:33 UTC 

<p><%= @timeinFile.to_time %></p> -------------> 2012-10-02 12:00:00 UTC

anyone plz tell me what wrong i have done.

Edit

<a href="http://www.cpsc.gov/en/Recalls/2013/Fitness-Anywhere-Recalls-Early-Model-Suspension-Trainer-Devices-Due-to-Fall-Hazard/" target="_blank">Fitness Anywhere Recalls Early Model Suspension Trainer Devices Due to Fall Hazard</a> (Tue, 02 Oct 2012 12:00:00 GMT) Fitness Anywhere has received 570 reports of the strap length adjustment buckles breaking with 13 reports of injuries. TRX suspension trainers sold from 2006 through 2009. </p> </body> </html> 

this is the line i am getting in @arr. next step was to partition with ( and then with ) to get date in round brackets...

Upvotes: 0

Views: 302

Answers (1)

Miotsu
Miotsu

Reputation: 1776

Well, why do you use @timeinFile in your code and @timeonsite in your tests?

#Error: undefined method `to_datetime' for nil:NilClass

basically means you are calling a method on a nil object, and I feel the error is triggered on the line BEFORE the if statement.

What happens when you put this check?

unless j.partition(')')[0].nil?
  @timeinFile=j.partition(')')[0].to_datetime
else
  @timeinFile = DateTime.now
end

If it doesn't give you an error you can go and find out why that value is nil.

Upvotes: 3

Related Questions