0

Consider we need to determine an expiry date for a contract such that after this date the contract will be destroyed as follows:

uint256 public expiryDate;

constructor(uint256 duration)
        public
        payable
    {
        owner= msg.sender;
        expiryDate = now + duration; 
    }

function destryContract() public {
        require(now >= expiryDate);
        selfdestruct(owner);
    }

Now, consider we need to calculate the exact duration for this expiry date, for example, we want to distroy the contract exactly after one month.

How to calculate the value of the duration variable as an integer?

  • 1
    The global unit now specifies the number of seconds elapsed since 1/1/1970. Therefore, you should pass the duration in seconds. It cannot be done accurately for one month, because this period of time is not defined accurately (i.e., it can be anything between 28 - 31 days). If you're OK with the approximation of one month as 30 days, then you can use 60 * 60 * 24 * 30. – goodvibration Jul 10 '18 at 10:28
  • 2
    If you take a look to the solidity documentation media.readthedocs.org/pdf/solidity/develop/solidity.pdf Section 7.4.4 (Time Units), it shows some examples. If you use as convention 30 days you could for instance write expiryDate = now() + dayToWait*1 days, so that afterwards you can compare expiryDate and now directly. Maybe if you want to spare a multiplication in solidity and the related gas cost it is better the @goodvibration 's approach ^^ – Briomkez Jul 10 '18 at 13:49
1

Base on their documentation http://solidity.readthedocs.io/en/v0.4.24/units-and-global-variables.html Time Units.

You can do expiryDate = now + duration * 1 days where the formula (duration * 1 days) will result to the equivalent unix epoch(this is in seconds) that you can store in your uint expiryDate.

Just note that the now property in solidity does not really refer to the actual DateTime when the transaction was executed in the real world like how DateTime.Now would say in JavaScripts, C# or any other programming languages. In solidity I beleive it refers to the time when the block was created and verified. They also warn most developers to keep in mind that now can be influenced by the miners.

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.