This part of own Q&A serial of posts which shares knowledge gained during work on one project
I was looking for a way to do actions link to global time, but obtaining current timestamp was not a obvious task.
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 community
Using ethers.js , the only way i know how you can get the current timestamp on the blockchain is by using the provider getBlockNumber() function to get the latest block number then use the provider getBlock() function to get details around the latest block. Finally when u have the block , the block object would have timestamp property which gives u the current time on the blockchain in seconds.
If you want the ms version of the please just multiply the seconds by 1000.
let latestBlockNumber = await provider.getBlockNumber(); let block = await provider.getBlock(latestBlockNumber); console.log(block.timestamp); let latestTimeStampInMs = block.timestamp * 1000; console.log(latestTimeStampInMs);
In the EVM there is no way to obtain it, however there are several workarounds.
The first one is based on the block's timestamp: each timestamp should be bigger than the parent's one, although nodes can manipulate timestamp especially when it promises profits to them, also blocks could be rejected during mining.
The second one is based on using the block’s number as they are ordered one-by-one and by knowing average block time execution calculate current time - unfortunately the time of block mining also might vary, especially with new ethereum updates. Seems like the timestamp of the block is the better option.