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.
Ethereum Stack Exchange is a question and answer site for users of Ethereum, the decentralized application platform and smart contract enabled blockchain. It only takes a minute to sign up.
Sign up to join this communityDate 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
You only need to use the keyword now
[more info]
Math.floor(Date.now() / 1000)
.
Jan 21, 2018 at 18:36
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;
}
}