1

According to the Solidity docs, you cannot precisely calculate years based on the block.timestamp. I have an interest function compounding on an annual basis, so I only care when a whole year has gone by. If there are 2.99 years gone by since the contract was deployed, the interest calculation will consider that 2 years.

What is the best way to do this?

Here is what I have:

    uint public InitialBlockTime; /*Which is set in the contract constructor.*/

    function CalculateYearsGoneBy() public {
        YearsGoneBy = ((block.timestamp - InitialBlockTime)/31556926);
    }

31556926 is the average amount of seconds per year. Block timestamps are based on the Unix Epoch.

| improve this question | | | | |
1

I think what you wrote seems fine. I might have written this instead:

(block.timestamp - InitialBlockTime) / 1 years;

But note that 1 years == 365 days, so it's not quite the same amount of time that you're using now. (I just find it easier to read/audit.)

| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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