Is there a way to access Date object in solidity like in JS? If so, wouldn't it be wrong to call solidity deterministic? So i guess if it called so, you can't. So the question is - how do you work with time? P.S. i would appreciate code snippets)
3 Answers
When a transaction is executed, it is done in the context of being part of a block. The block includes a timestamp (in seconds since 1970), which your contract code can refer to by the name block.timestamp.
The timestamp is set by the miner who mines the block and nobody can be sure at what time they really mined it, so it may not be exactly accurate. However, it must be later than the previous block, and other miners will tend to reject a time set in the future, so it can be relied on within reasonable tolerances.
Since what the network is validating for each transaction is not the current time at the point of validation but the time as declared by the miner who mined the block, the result is deterministic.
The JavaScript date object also provides functions like getting the day of the week or month of the year. These are not natively provided in the EVM, but you can write or use a library to help you with them. Often it is practical for the contract to deal only in timestamps, and for applications - which often consist of HTML/JavaScript pages interacting with Ethereum contracts - to use JavaScript functions to format them to display then to the user.
- 16,897
- 1
- 29
- 58
No, In solidty there is no Date object which will give you the actual time, we can only get the timestamp of the block in which the contract is invoked, which is deterministic. You can use now keyword or block.timestamp in solidity to get the timestamp of the current block. This can be used to work with time. Reference to an auction contract is here.
- 1,019
- 6
- 11
Try https://github.com/pipermerriam/ethereum-datetime. It works with a unix-style uint timestamp under the hood. You get a DateTime object with year, month, day, hour, minute, second and even the weekday.
- 21
- 1
nowakablock.timestamp, each time it is called by a transaction it will log the time declared in the block containing the transaction. This will be approximately the time the miner mined the block, but they can fudge it a bit. – Edmund Edgar Jun 18 '17 at 08:45