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.