Block timestamps in Ethereum provide timing information for transactions and smart contracts. Understanding how to work with them is essential for time-sensitive applications.
// Get block timestamp
const getBlockTimestamp = async (blockNumber) => {
const block = await web3.eth.getBlock(blockNumber);
return block.timestamp;
};
// Calculate average block time
const getAverageBlockTime = async (blockCount = 100) => {
const latestBlock = await web3.eth.getBlockNumber();
const oldBlock = await web3.eth.getBlock(latestBlock - blockCount);
const newBlock = await web3.eth.getBlock(latestBlock);
return (newBlock.timestamp - oldBlock.timestamp) / blockCount;
};