3

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!

1

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.

https://github.com/ethfinex/efx-trustless-vol/blob/master/src/lib/getBlockByTime.js

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
  • Thank you, this is the closest answer to what I've been looking for. – ZitRo yesterday
1

Not really.

Your best bet is to take a sample size loop from latest to latest - {x} block and get the moving average of block time creation. From there you can estimate a block number to get the block time from and loop until you cross the time you need.

1

QuickBlocks has a command line program called 'whenBlock' that takes either a date (or timestamp) and takes the block number that occurred just prior, or a block number and returns the date and timestamp of that block. You can download QuickBlocks here: http://github.com/Great-Hill-Corporation/quickBlocks.

1

This is an old question, but recently I wrote a plugin for this kind of task. Usually, it makes fewer requests than Ethfinex's script does (usually, not always 😂).

Take a look: https://github.com/monosux/ethereum-block-by-date

  • Great work! It would be even greater if you could avoid using moment.js as a dependency (it's a really heavy module). Thanks! – ZitRo yesterday

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.