I've noticed that this always returns the same value:

 function getNow() public constant returns (uint) {
        return now;

But when I use the now keyword in an function that changes the state of the network then it seems to work.

Can someone explain why this happens? Is there a way to use "now" in a view function?

Basically I'm just trying to set a timer and figure out how long the timer has left without paying any gas.



The issue is that now is an alias for block.timestamp. In the context of a transaction, this is the timestamp of the block that the transaction is a part of. In a call, I believe the function is evaluated in the context of the latest block. In my testing, a function such as the one you described returns the timestamp matching the most recent block. If you call it repeatedly, you should see the return value change every time a new block is mined.

In any case, you don't need this for the purposes of your countdown... you can just use the current Unix epoch time, which you can easily get in JavaScript or any other programming language.


now won't evaluate properly in view function. Reference (point 8): https://solidity.readthedocs.io/en/develop/contracts.html#functions

  • I don't understand your answer. Point 8 is "Using inline assembly that contains certain opcodes," which doesn't seem relevant. now certainly does not modify any state. Note that the code sample in the documentation shows a view function that uses now, and the Solidity compiler emits no warning for that code. See my answer for what I believe is the issue.
    – user19510
    Feb 9 '18 at 23:23
  • As I understood it, now is considered as an opcode in the example - it's the only non-constant (except the input variables which are totally ok in view functions). I interpreted that the example code is for the point 8. Feb 10 '18 at 7:03
  • I believe your interpretation was incorrect.
    – user19510
    Feb 10 '18 at 7:06

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.