I have setup a subscription plan which will automatically charge the users every month, every three months and every year. The problem is, how can I calculate the exact date to charge the user? We can't charge every 30 days right? Because not all months have 30 days. If we charge on the date bought, people who bought the plan on January 30 won't be billed on February because there's no 30 in February. It's a bit of a complex problem. How can I solve this?
PS : Im using ruby on rails
You could store the subscribed_on
date and the number_of_payments
the user already made. Then calculate the next payment date by increasing the number_of_months
and using the >>
method on date. >>
takes the number of days in a month into account:
# at subscription date and first payment
subscribed_on = Date.today # in this 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 of Date#>>
d >> n
→date
Returns a date object pointing
n
months afterself
. Then
should be a numeric value.
This does not only return correct dates, it also allows optimized queries for next_payment_date
and statistics like the average length of subscription time in months.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With