Search code examples
ruby-on-railsrubypostgresql

Rails check if expiration date is 1 year from today


I'm trying but date format is not correct, I'm also doing it in a controller

Date format of expiration_date in database is 2025-01-15 08:00:00.

if @car_subscription.expiration_date.present?  && @car_subscription.expiration_date == @car_subscription.expiration_date == Date.today + 1.year 
   @car_subscription.update(new_cars: @car_subscription.new_cars = 20)
end

Solution

  • You are trying to compare a DateTime instance (@car_subscription.expiration_date) and a Date instance (Date.today + 1.year). Actually, technically it's not an incorrect comparison.

    But if we assume that expiration_date field is a timestamp that is created depending on creation of the record (it may have very different hour/minute/second values) and return value of Date.today + 1.year value will refer first second of that day, the probability of equality here will be very low.

    If you want to check if expiration_date is equal to one year from today, casting this field as date object would be healthier for comparison.

    So you can try something like this:

    if @car_subscription.expiration_date.present?  && @car_subscription.expiration_date.to_date == Date.today + 1.year 
      @car_subscription.update(new_cars: @car_subscription.new_cars = 20)
    end
    

    By the way, in your snippet, you wrote below statement twice @car_subscription.expiration_date. I assume this as a typo.

    Thanks to @Stefan for correction.