Skip to main content

Introduction

In this tutorial, you’ll learn how to find the block number that was mined closest to a specific date or Unix timestamp. This is useful for querying historical blockchain data at specific points in time, such as getting token balances or prices at a particular date. We’ll use the following Moralis API endpoint:

Prerequisites

Step 1: Set Up Your Project

Create a new directory for your project and initialize it:
mkdir get-block-by-date && cd get-block-by-date
npm init -y

Step 2: Create the Script

Create a file called index.js and add the following code:
// index.js
const API_KEY = 'YOUR_API_KEY';

async function getBlockByDate() {
  // Find the block closest to January 1, 2024
  const date = '2024-01-01T00:00:00Z';

  const response = await fetch(
    `https://deep-index.moralis.io/api/v2.2/dateToBlock?chain=eth&date=${encodeURIComponent(date)}`,
    {
      headers: {
        'X-API-Key': API_KEY,
      },
    }
  );

  const data = await response.json();
  console.log(JSON.stringify(data, null, 2));
}

getBlockByDate();
Replace YOUR_API_KEY with your actual Moralis API key.

Step 3: Run the Script

Execute the script to find the block:
node index.js

Example Response

{
  "block": 18908895,
  "date": "2024-01-01T00:00:11.000Z",
  "timestamp": 1704067211,
  "block_timestamp": "2024-01-01T00:00:11.000Z",
  "hash": "0x..."
}

Understanding the Response

FieldDescription
blockThe block number closest to the requested date
dateISO timestamp of when the block was mined
timestampUnix timestamp of the block
block_timestampSame as date, in ISO format
hashThe block hash

Next Steps