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?
You 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
}