How do I calculate the next renewal date for my subscription?

I have set up a subscription plan that will automatically charge users every month, every three months, and every year. The problem is, how can I calculate the exact date for charging the user? Can't we charge every 30 days? Because not all months have 30 days. If we charge on a purchased date, people who bought the plan on January 30th won't be billed in February because there aren't 30 in February. This is a bit of a tricky issue. How can I solve this?

PS: I'm using ruby ​​on the rails

+3


source to share


1 answer


You can save the date subscribed_on

and number_of_payments

user already made. Then calculate the next payment date by incrementing number_of_months

and using the >>

date method . >>

takes into account the number of days per month:

# at subscription date and first payment
subscribed_on      = Date.today # in the example: 2015-01-30
number_of_payments = 1
next_payment_date  = subscribed_on >> number_of_payments
#=> 2015-02-28

# after next payment (on 2015-02-28)
number_of_payments = number_of_payments + 1
next_payment_date  = subscribed_on >> number_of_payments
#=> 2015-03-30

# after next payment (on 2015-03-30)
number_of_payments = number_of_payments + 1
next_payment_date  = subscribed_on >> number_of_payments
#=> 2015-04-30

      

From the documentation



d >> n

β†’ date

Returns a date object indicating n months after itself. The n value must be numeric.

This leads not only to the correct dates, but also to optimized queries for next_payment_date

, and statistics - the average length of the subscription period per month.

+6


source







All Articles