Solidity is a programming language to write smart contracts on the Ethereum blockchain. Precise timings have an important role to play in smart contracts since on many occasions it has to ensure the execution of the code based on conditions that include time constraints.
Solidity has provided developers with many time units which are used as suffixes for better code readability and can be used to denote various time duration.
Time Units in Solidity
There are 5 valid time units in Solidity. These are seconds, minutes, hours, days, and weeks.
- The time unit years have been removed from Solidity versions 0.5.0 and above since a year can have either 365 or 366 days(in case of leap year) and hence to avoid ambiguity the suffix was deprecated.
- Since a month can have 28, 29, 30, or 31 days, there is no such unit for months in Solidity.
1 seconds == 1 seconds
1 minutes == 60 seconds
1 hours == 60 minutes == 3600 seconds
1 days == 24 hours == 86400 seconds
1 weeks == 7 days == 604800 seconds
Syntax Rules and Properties of Time Units
1. These time units are used as suffixes after integer numbers, i.e., you have to append the time unit to the integer value.
Example:
uint t = 5 seconds; // variable 't' will store the value 5
2. These suffixes cannot be used after variables. They cannot be appended to floating-point numbers.
Example:
uint a = 100;
uint b = a minutes; // Compilation error, time unit can't be appended after variables
uint c = 5.5 minutes; // Compilation error, time unit can't be appended after floating-point numbers
3. The base or the default time unit in Solidity is seconds. When you assign a time unit after a number, the equivalent number of seconds is stored in the variable.
Example:
uint a = 5 minutes; // variable 'a' stores the integer value 300 since 5 minutes = 300 seconds
uint b = 1 hours; // variable 'b' stores the integer value 3600 since 1 hours = 3600 seconds
4. While performing arithmetic operations, all the time units are converted into an equivalent number of seconds.
Example:
uint a = 10 + 5 minutes; // 5 minutes is converted to 5*60 = 300 and then added to 10. Thus, variable 'a' stores the value 10 + 300 = 310
uint b = a + 20 seconds; // variable 'b' stores the value 310 + 20 = 330
uint c = 2 hours + 1 days; // variable 'c' stores the value 2*3600 + 1*86400 = 93600
uint d = 5 minutes + 30 seconds // instead of writing 5.5 minutes, one can write in this way
Purpose of Time Units
The entire purpose of time units is to write time duration in human-readable form since a large duration of time represented in seconds would be illegible. Time units make the code look more readable.
Let's explain the concept and usage of time units via a Solidity Program. The contract named Timeunits_Example will get us the number of seconds and minutes that elapsed after the calling of the setStartTime() function.
Solidity
// SPDX-License-Identifier: GPL-3.0
pragma solidity >= 0.5.0 < 0.9.0;
contract Timeunits_Example {
// Declaring a state variable that will
// store the current block timestamp
// as seconds since unix epoch(January 1, 1970)
uint256 public startTime;
// setting the startTime variable
function setStartTime() public {
startTime = block.timestamp;
}
// calculates numbers of seconds that
// have been elapsed since the startTime
// variable was set
function elapsedSeconds() public view returns (uint256) {
return (block.timestamp - startTime);
}
// calculates numbers of minutes that have been
// elapsed since the startTime variable was set
function elapsedMinutes() public view returns (uint256) {
// Both block.timestamp and startTime are in seconds
// Dividing them by 1 minutes == 60 seconds to find
// equivalent number of minutes
return (block.timestamp - startTime) / 1 minutes;
}
}
Output :
Similarly, we can add more functions to the above contract to find elapsedDays, and elapsedWeeks since the startTime was set. We can edit the above contract and use a single function to get the time elapsed.
Solidity
// SPDX-License-Identifier: GPL-3.0
pragma solidity >= 0.5.0 < 0.9.0;
contract Timeunits_Example {
// Declaring a state variable that will
// store the current block timestamp as
// seconds since unix epoch(January 1, 1970)
uint256 public startTime;
// setting the startTime variable
function setStartTime() public {
startTime = block.timestamp;
}
// calculates the time in dd:hh:mm:ss format.
// For example, 3702 seconds will be 0 dd, 1 hh,
// 1 mm, 42 ss that is 0 days, 1 hours, 1 minutes
// and 42 seconds
function elapsedTime() public view returns (uint256 dd,
uint256 hh,
uint256 mm,
uint256 ss) {
dd = (block.timestamp - startTime)/1 days;
hh = (block.timestamp - startTime)/1 hours - (dd * 24);
mm = (block.timestamp - startTime)/1 minutes - (hh * 60) -
(dd * 24 * 60);
ss = (block.timestamp - startTime)/1 seconds - (mm * 60) - (hh * 60 * 60) -
(dd * 24 * 60 * 60);
}
}
Output :
The time elapsed is 3 minutes 12 seconds, i.e., 192 seconds
Similar Reads
SQLite Date and Time
In the world of database management, understanding how to handle dates and times is important. SQLite is a popular relational database management system that offers a robust set of functions and features for working with date and time data. From storing timestamps to performing date calculations, SQ
5 min read
Time Durations in Golang
Operations related to time and date are a crucial part of software development (example log keeping). Go standard library provides a time package that has many functions and methods to deal with date and time. The operating system measures two types of time "Wall clock" time and "Monotonic" time. Wa
3 min read
Tensorflow.js tf.time() Function
Tensorflow.js is an open-source library that was developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment. The tf.time() function is used to execute the stated function, f() as well as return a promise in order that determine
2 min read
Perl | Date and Time
Perl is one of the most feature-rich programming languages. Perl is portable and cross-platform. Perl can run on over 100 platforms with highly integrated text processing ability. Perl contains the features of different languages like C, sed, awk, and sh etc. which makes the Perl more useful and pro
3 min read
Python time.thread_time() Function
Timer objects are used to represent actions that need to be scheduled to run after a certain instant of time. These objects get scheduled to run on a separate thread that carries out the action. However, the interval that a timer is initialized with might not be the actual instant when the action wa
2 min read
java.time.LocalDate Class in Java
Java is the most popular programming language and widely used programming language. Java is used in all kind of application like as mobile application, desktop application, web application. In this Java java.time.LocalDate class is imported which represents to display the current date. java.time: It
4 min read
java.time.LocalDateTime Class in Java
java.time.LocalDateTime class, introduced in Java 8, represents a local date-time object without timezone information. The LocalDateTime class in Java is an immutable date-time object that represents a date in the yyyy-MM-dd-HH-mm-ss.zzz format. It implements the ChronoLocalDateTime interface and in
4 min read
8051 Timers and Counters
8051 microcontrollers are mainly used to speed up our tasks because they are very easy to use and they are also fast to complete tasks easily. These microcontrollers have one main feature which is Timers and counters. This feature is widely used in microcontrollers to measure the time and as well as
9 min read
How to time an operation in milliseconds in Ruby?
In this article, we will learn about how to time an operation in milliseconds in Ruby. We can perform this using different approaches. Table of Content Using Benchmark.realtimeUsing Process.clock_gettimeUsing Time classUsing Benchmark.realtimeBenchmark.realtime method to measure the time taken for t
2 min read
Dates and Time in MATLAB
MATLAB provides many ways to deal with date and time in form of DateTime, calendar duration, and duration data types. These data types do not only support storing and representing date-times but, also allow operations on date time. We shall look at these three data types separately. DateTimeThe date
2 min read