import {providers} from "ethers";
const provider = new providers.InfuraProvider("homestead")
async function main() {
    provider.on("block", (blockNum)=> {
        console.log(blockNum+ ": " +new Date(Date.now()))
    })
}
main()
From code above output:
13261128: Mon Sep 20 2021 14:57:42 GMT+0800 
13261129: Mon Sep 20 2021 14:58:14 GMT+0800 
13261130: Mon Sep 20 2021 14:58:42 GMT+0800 
13261131: Mon Sep 20 2021 14:58:58 GMT+0800 
From etherscan.io:
Sep-20-2021 06:57:12 AM +UTC (https://etherscan.io/block/13261028)
Sep-20-2021 06:57:23 AM +UTC (https://etherscan.io/block/13261129)
Sep-20-2021 06:58:07 AM +UTC (https://etherscan.io/block/13261130)
Sep-20-2021 06:58:38 AM +UTC (https://etherscan.io/block/13261131)
My question
My computer's clock is exact what the time is, why the difference between this two way?
Can I get the accurate block time from ethers.js API or can get it from the other way?
Timestamp of the block is in UTC (hence the timezone offset as mentioned by @Dmitriy Kashirin) and does not represent exact time the block has been mined as it is set by the miner. Therefore, slight offsets are allowed and timestamp shouldn't be used as the source of randomness for sensitive contracts. Read more here.
Yes, the timestamp of the exact block can be obtained fairly simple using ethers.js with RPC provider:
const RPC = "RPC_OF_THE_NETWORK";
const blockNumber = 1; // number of the block you want to get timestamp of
const provider = new ethers.providers.JsonRpcProvider(RPC)
const timestamp = (await provider.getBlock(blockNumber)).timestamp;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With