Saturday, April 18, 2009

Comparing two dates


Share at Facebook

Depending upon your language, there may be built in functions to compare two dates to get the smaller, or larger date. The functions may be different on name on different languages, or it can have different formatted parameters.

I'm going to show you how to compare two dates, and get the bigger/smaller date using String Compare. I assume you have two dates, and both are same format. For example you have two dates having YYYY-MM-DD format. You can now easily perform String compare on the two dates. Depending upon -1,1,0 you can easily decide which one is smaller or greater. This little tricks help you to compare your dates in php, perl, java, ruby, C/C++, python types of language. You just know how to compare string on those language.

For example, in PHP, here is a small piece of code to compare two dates.

$date_1 = "2009-09-12";
$date_2 = "2009-09-17";
print strcmp($date_1, $date_2);


At perl using ge or le string comparing operator.
$date_1 = "2009-09-12";
$date_2 = "2009-09-17";
if($date_1 le $date_2){
## process
}


Similar will be for other languages.




No comments: