I need to compare dates in solidity, so as to complete a business rule. There is no date type in solidity which ca be used to store date and perform calculations on it. So help in this regard will be very great.
2 Answers
In your case you will be using dates in your contracts quite a lot, so my suggestion to you is to make a library for date manipulation.
Here are some lines from the documentation: Suffixes like seconds, minutes, hours, days, weeks and years after literal numbers can be used to convert between units of time where seconds are the base unit and units are considered naively in the following way:
1 == 1 seconds
1 minutes == 60 seconds
1 hours == 60 minutes
1 days == 24 hours
1 weeks == 7 days
1 years == 365 days
Take care if you perform calendar calculations using these units, because not every year equals 365 days and not even every day has 24 hours because of leap seconds. Due to the fact that leap seconds cannot be predicted, an exact calendar library has to be updated by an external oracle.
These suffixes cannot be applied to variables. If you want to interpret some input variable in e.g. days, you can do it in the following way:
function f(uint start, uint daysAfter) public {
if (now >= start + daysAfter * 1 days) {
// ...
}
}
The now variable is used as:
now (uint): current block timestamp (alias for block.timestamp)
Below is the sample function that calculates the bonus based on the weeks from the time of the contract creation. Where START is assigned as a variable with Unix timestamp format. Hope this helps you.
function getRate() constant internal returns(uint) {
if (START + 1 weeks > now) {
return 1000; //number of tokens in week 1
} else if (START + 2 weeks > now) {
return 750; //number of tokens in week 2
} else if (START + 3 weeks > now) {
return 500; //number of tokens in week 3
} else {
return 250;
}
}
now
which you can use to compare with unix timestamp numbers.