I am writing a contract that will calculate interest on a periodic basis using the exact number of days in each period. So, for example, if I use Jan 1st 2018 to March 31st 2018 as an example, there would be 90 days in that period. I then need to move the period forward by 3 months to capture the next quarter of interest.

The specific code I am using now is:

function nextPeriod() public {
    lastPeriodDate = currentPeriodDate;
    currentPeriodDate += 1 years/4;

This works but it is approximate.

Anyone have any suggestions?



1 Answer 1


In my opinion it might be helpful to reframe the question with a little more precision.

When you say "I need to", it creates a little doubt about what's supposed to happen. It's hard to say if you need the contract to determine this, or you need the contract owner to determine this, or someone else. This will be important.

Solidity doesn't have a month word and I suspect this it due to inherent ambiguity, since months have different numbers of days. It seems "month" and "30 days" are casually interchanged in informal conversation but contracts are roughly the opposite of informal. One will have to define, precisely, what is meant by "month" in the context of the contract.

Setting aside the imprecision of timestamps, you could do something like:

now + 30 days

That is, in the case that the contract needs to be able to figure it out.

Or, you could outsource it to an Oracle.

function setNextMonth(uint nextMonth) public onlyOwner ...

That is, in the case that you want to figure out exactly when each month starts and you don't want to over-complicate the contract.

A third approach would be to perform a rather cumbersome calculation, taking into account the different number of days in each month and leap years. This pushes (pretty hard) against the ideal of minimalism in contract design.

You could even imagine crowd-sourcing the computation via opinion markets, since the correct choice is obvious. In that construction, "next month" is the block number decided by a majority on a platform like Auger or Gnosis.

Hope it helps.

  • Thanks Rob. I see your points. I did edit the question to add more precision. I also get what you are saying. I will not try and abuse Solidity to do what it was not designed to do, but rather put the heavy lifting in the Javascript front-end. Thanks for your effort in giving me a complete and lengthy answer. May 12, 2018 at 13:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.