简体   繁体   中英

strptime error with Rails 4

I am creating a simple validation inside of my model that checks to see if a date ( to_date ) is before the current date.

The format the user submits the to_date in is %m/%d/%Y or for example, 03/15/2016 .

My issue, is rails is throwing me an invalid date error, although I have triple checked that the date is in the correct format.

Here is my validation:

validate  :date_not_before_now

def date_not_before_now
  if Date.strptime(self.to_date, '%m/%d/%Y').strftime("%Y-%m-%d") < Time.now.localtime.strftime("%Y-%m-%d")
  errors.add(:dates, "should not be in the past.")
end

end

Any help figuring out why this isn't working would be much appreciated.

try this when validating date

validates :date_field, presence: true, date: {on_or_before: :today}

def today
  Date.today
end

You can try this.

validate  :date_not_before_now

def date_not_before_now
  if ( Date.strptime(self.to_date, '%m/%d/%Y') < Time.now.localtime.to_date)
    errors.add(:dates, "should not be in the past.")
  end
end

Tried in console and worked see the following eg

Date.strptime("03/15/2016", '%m/%d/%Y') < Time.now.localtime.to_date
## Output
=> true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM