[Ethereum] How to get the block number which is the closest to a given timestamp


Is there any method(ology) in web3 which allows to get the block number at a given date?

In particular, I have two dates as an input and I want to effectively get all events between those two dates. I know that I can do this by having block numbers:

contract.Event({}, { fromBlock: 100000, toBlock: 121212 })

But is it possible to do so with Dates? Thanks!

Best Answer

Ethfinex just published a function that does exactly that.

It's to "pixel perfect" but it's working really well so far, you give it a timestamp and it will walk the blockchain backwards until it finds a block that is very close.

During my tests it always found the nearest block, you might need to tweak it a little bit more.


here are some results

tgt timestamp   -> 1545523200
tgt date        -> 2018-12-23T00:00:00Z

block timestamp -> 1545523212
block date      -> 2018-12-23T00:00:12Z

requests made   -> 3

tgt timestamp   -> 1545609600
tgt date        -> 2018-12-24T00:00:00Z

block timestamp -> 1545609592
block date      -> 2018-12-23T23:59:52Z

requests made   -> 4
Related Topic