5

What's the best way to calculate with dates in solidity, in particular, getting the total number of days between the start date and end date?

Also

What's the best way to get the current date/time in solidity?

Much appreciated.

9
  • What's the best way to calculate with dates in solidity, in particular, getting the total number of days between the start date and end date?

Date are stored in the Unix epoch format (timestamp) which consists in an integer of the number of seconds since 1970-01-01.

If you want to compare two dates, it's simple math. For example:

uint startDate = 1514764800; // 2018-01-01 00:00:00
uint endDate = 1518220800; // 2018-02-10 00:00:00

uint diff = (endDate - startDate) / 60 / 60 / 24; // 40 days 
  • What's the best way to get the current date/time in solidity?

You only need to use the keyword now [more info]

  • How do you calculate the timestamp? – H.Thiam Jan 21 '18 at 18:32
  • Depending of the language you use to interact with the smart contract. In JavaScript, you can do: Math.floor(Date.now() / 1000). – Greg Jeanmart Jan 21 '18 at 18:36
0

Within the Ethereum Virtual Machine, there isn't a way to get the current time, other than the block time.

To get current block time stamp we can directly use block.timestamp in solidity. Its returns a time in unix timestamp.

Ethereum provides Time unites to facility date computation to a particular level, refer the following document. https://solidity.readthedocs.io/en/develop/units-and-global-variables.html#time-units

Few examples: Following method returns the timestamp of 30 days before.

function getTime () public view returns(uint256 time){
        return block.timestamp - 30 days;
    }

To compare validity (LastTimeStamp is variable contains old timestamp)

function checkExpiry() public view returns(bool success){

    if (LastTimeStamp +30 days >= block.timestamp)
     {
         return true;
     }
        else
     {
         return false;
     }     
}

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.