0

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.

0

2 Answers 2

1

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);
0

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.

1
  • Within smart contract you can get timestamp like this block.timestamp;
    – Gleichmut
    Sep 30, 2022 at 10:31

Not the answer you're looking for? Browse other questions tagged or ask your own question.