7

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?

2 Answers 2

9

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);
   }
}
4
  • 1
    Thank You, perfect answer, exactly to the point . Commented Aug 6, 2019 at 17:30
  • 1
    Great. Feel free to "accept" the answer, so that future viewers will know that this answer solved your issue. Commented Aug 6, 2019 at 17:52
  • 1
    I checked entire page, and didn't found any button like "accept", don't know where that gone, here is only two options "share" and "edit" , otherwise I would not have replied thanks in comment because accept=thanks Commented Aug 7, 2019 at 10:44
  • There is a check mark under the up and down vote arrows. Try clicking on that to accept. Commented Aug 7, 2019 at 14:35
3

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
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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