[Ethereum] How to get current time

block-intervalsoliditytimestamp

My project is fully based on time. Is there any way to get current time without using NOW? NOW is just returns time when block was mined and always shows "transaction will fail" when I do require(now > 1517735968), but if I ignore it, everything works fine.

Best Answer

You can use Oraclize service.


What you need:

  • basic understanding how Oracles work
  • choose which API you want to use (in our case we can use Short Answers API)
  • sign up on Wolfram to get your AppId

By making simple custom query in my browser:

https://api.wolframalpha.com/v1/result?i=Timestamp+now%3F&appid=YOUR-APPID

I was able to get result:

1517736939 Unix time

Short Answers API


I realised when I posted this answer that there is a shorter way to make your query from contract. Below you can see working example which you can test in browser-solidity. Just click create button and after couple of times clicking on timestamp it should show: string: 1517738717 (timestamp at a time I was writing it).

pragma solidity ^0.4.0;
import "github.com/oraclize/ethereum-api/oraclizeAPI.sol";

contract WolframAlpha is usingOraclize {

    string public timestamp;

    event newOraclizeQuery(string description);
    event newTimestampMeasure(string timestamp);

    function WolframAlpha() {
        update();
    }

    function __callback(bytes32 myid, string result) {
        if (msg.sender != oraclize_cbAddress()) throw;
        timestamp = result;
        newTimestampMeasure(timestamp);
    }

    function update() payable {
        newOraclizeQuery("Oraclize query was sent, standing by for the answer..");
        oraclize_query("WolframAlpha", "Timestamp now");
    }
} 
Related Topic