If you're hesitant to use APIs and prefer relying on estimates, then I suggest going that route.
Here's how you can calculate the estimated time for a specific block:
- Start by determining the average time it takes to generate a new block. According to data from PolygonScan, it's around
2.5s
.
- Next, figure out the total number of blocks that have already been produced. As per my last check, there were
36996889
blocks generated.
- Finally, select the block number you want to estimate the time for. Let's say we choose block
36996800
as an example here.
To approximate the time when the target block was generated, you can utilize this algorithm:
const currentBlockNumber = 36996889;
const targetBlockNumber = 36996800;
const averageTimePerBlock = 2.5;
// Calculate the number of blocks since the target block
const numberOfBlocks = currentBlockNumber - targetBlockNumber;
// Calculate the approximate time when the target block was created
const approximateTimeInSeconds = numberOfBlocks * averageTimePerBlock;
// Estimate the date and time the target block was generated
const dateAndTimeCurrentBlockWasProducedAt = new Date(1671405095000); // Timestamp when the current block was produced
const approximateTimeInMilliseconds = dateAndTimeCurrentBlockWasProducedAt.getTime() - (approximateTimeInSeconds * 1000);
const approximateDate = new Date(approximateTimeInMilliseconds);
console.log(`The target block was approximately generated on ${approximateDate}.`);