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.

1 Answer 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.)

Your Answer

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

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