Working with Dates and Time in Solidity using timestamps?


Solidity does not support Date or DateTime by default. There are no such conceps and we’d have to substitute it with Integers or Strings.

Getting the Time

Do not rely on the timestamps returned by Solidity. Time accuracy is tied to the time when the block was mined.

block.timestamp will give you an integer value of the timestamp. You can store the timestamp value in your contract by using uint since it’s always going to be a positive value.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

contract TimestampStorage {
    uint256 public storedTimestamp;

    function storeCurrentTimestamp() public {
        storedTimestamp = block.timestamp;
    }

    function getStoredTimestamp() public view returns (uint256) {
        return storedTimestamp;
    }

    function getCurrentTimestamp() public view returns (uint256) {
        return block.timestamp;
    }
}

Retrieving and handling

Handling retrieved data in the frontend is slightly more complicated because JavaScript has limitations of how large a number can go. You can check the limits in your browswer by running Number.MAX_SAFE_INTEGER.

To prevent any overflow errors, libraries like ethers.js will use a custom implementation like BigInteger. If we want to do simple display or use it with other libraries that don’t support BigInteger, we’d have to convert them into Number or BigInt, if your browser supports it.

storedTimestamp // <- BigNumber coming from ethers.js
const timestampNumber = storedTimestamp.toNumber() // convert to Number or bigNumber.toString()
const date = new Date(timestampNumber * 1000); // Multiply by 1000 to convert seconds to milliseconds