Web3j - How to get timestamp for contract creation time?

1.1k views Asked by At

I've successfully deployed a contract using

Optional<TransactionReceipt> receipt = Contract.deploy(...).send().getTransactionReceipt();

The receipt how ever doesn't return a timestamp. It returns the transaction hash and the blocknumber.

How would I use the web3j library to get the timestamp of the contract creation time?

2

There are 2 answers

1
tenbits On

You get the timestamp from the block (where the contract creation transaction was included).

let block = await web3.eth.getBlock(nr);
let date = new Date(Number(block.timestamp) * 1000)
0
gbii On

If you have a transaction receipt, you can get a Date object as follows.

TransactionReceipt txnReceipt = ...
...
EthBlock txnBlock = web3j.ethGetBlockByHash(txnReceipt.getBlockHash(),true).send();
long txnBlockTimestamp = txnBlock.getBlock().getTimestamp().longValueExact() * 1000;
Date blockDate = new Date(txnBlockTimestamp);