Clocks showing difference times with a white background in structured rows and columns with a white glow around each clock.
UsingTime in Solidity
December 7th, 2020

Special Variables and Functions

There are special global variables and functions that always exist in the namespace and are mainly used to provide information about the blockchain or are general-use utility functions.

One example of such a global variable is the block variable, which enables you to acquire useful information regarding the properties of the blocks on the blockchain.

Time locks are a common use-case, when you may be interested in locking tokens for a pre-determined timeframe, for example.

When you are interested in time, you may be want to know the block.timestamp, which represents the current block timestamp represented in (uint) unix epoch time, is calculated in seconds.

Another potentially useful variable is block.number, which represents the current block number.

More concretely, in the event that you are interested in locking tokens, you may consider using block.timestamp to specify a require condition wherein which the block.timestamp is ≥ lock expiration time (represented in unix epoch time).

Solidity makes things even more convenient by providing time units, such as "days" and "years", which are particularly useful when you are interested in computing longer time spans, so you may consider working these convenient tools to help you save… time, kek.

Let's checkout a simple contract that does nothing beyond remembering when it was created, voila!

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

    contract Time {
        uint256 public createTime;

        constructor() {
            createTime = block.timestamp;

TLDR; blocks in the blockchain includes a timestamp specified as the number of seconds since the Unix epoch. Time values are integers (uint).

Smart contracts written in Solidity may access the timestamp of the current block as now or block.timestamp.

Additional Notes

  • The alias now was removed in Solidity 0.7.0, so we will use block.timestamp.

  • Solidity provides convenient time units like days and years, which are helpful in computing time spans and may be accessed by literally using "days" or "years" as a unit.