14

Is there a way for a contract to be able to get the exact time someone called a function in it?

For example, if someone sends funds to the contract address, is there a timestamp recorded by the blockchain that would give the received time of this transaction?

And if so, how would I get this value in Solidity and would the timestamp of this transaction be modifiable by the user in any kind of way once it is sent?

3 Answers 3

18

A transaction doesn't have a timestamp. However, every block provides a timestamp (when it was collected), but if the time is critical for you, don't refer to this timestamp because a miner could modify it by about 900s. Instead, you could use block.number.

1- current block timestamp is returned by now:

e.g.

contract Test {
    function Time_call() returns (uint256){
        return now;
    }
}

Time_call() will return something like 1478431966 (which you could convert into a readable form in https://www.unixtimestamp.com/).

2- block number is returned using block.number:

 function Time_call() returns (uint256){
        return block.number; 
    }

to get the call time, you could use the block.number and the block time (an average).

Edit: if you want when the transaction was sent, use JavaScript in your Dapp to get the current time var seconds = new Date().getTime() / 1000; and send it in the data field within your transaction.

6
  • @Badr_Bellaj if I am not mistaking, this returns the timestamp of the block and not of the time the transaction was received/sent. Am I correct? Because what I need is to get the time the transaction was sent not the time it was executed at.
    – Pabi
    Nov 6, 2016 at 13:18
  • 2
    it is impossible to get when the transaction was sent, there is no timestamp in the transaction. besides, we don't know how time it was on the pool or when it was signed. However you could write a dapp using web3js which send such information withing the transaction.
    – Badr Bellaj
    Nov 6, 2016 at 13:27
  • check the edit for more details
    – Badr Bellaj
    Nov 6, 2016 at 13:39
  • @Badr_Bellaj How do you then interact with data in the data field in solidity?
    – Pabi
    Nov 6, 2016 at 13:41
  • 1
    by using msg.data
    – Badr Bellaj
    Nov 6, 2016 at 13:53
0

You can simply use the keyword now to get the current timestamp.

0

You can use block.timestamp to get the current block timestamp

Reference:

Solidity Docs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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