I want to get the timestamp of an event.
How can I get time of event fired, if the event data does not contain any time value?
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 communityYou can do this by checking the timestamp of the block that the event was included in. For something like web3.js, you can use getBlock
:
web3.eth.getBlock(blockHashOrBlockNumber [, returnTransactionObjects] [, callback])
Additionally, you can include the timestamp in the event itself. It would look like this:
pragma solidity ^0.5.5;
contract MyEvetTest {
event MyEvent(uint256 timestamp);
function myFunction() public {
emit MyEvent(block.timestamp);
}
}
If you didn't store timestamp in event, you can parse like this
const getTimeByBlock = async(txHash) => {
const blockN = await web3.eth.getTransaction(txHash)
const blockData = await web3.eth.getBlock(blockN.blockNumber)
return blockData.timestamp
}