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
Time Units in Solidity
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.