In the SQL Server, strings in the date format can be directly converted to each other to compare dates. However, can we directly compare dates in. NET? The answer is certainly yes.
See the following code
StrStartDate = this. dtpStartDate. Value. ToString ("yyyy-MM-dd ");
StrEndDate = this. dtpEndDate. Value. ToString ("yyyy-MM-dd ");
// Determine whether the start date is later than the end date
If (string. CompareOrdinal (strStartDate, strEndDate)> 0)
{
MessageBox. Show ("the end date must be [greater than] The start date! "," Error message! ", MessageBoxButtons. OK, MessageBoxIcon. Error );
This. dtpEndDate. Focus ();
Return;
}
Of course, it is mainly to convert the date data type into a string for comparison, because the string comparison is mainly to convert it into a single character for comparison, of course, here we use the CompareOrdinal () method that comes with string to compare. NET Description, see. This method has two overload functions:
//
// Summary:
// Compare two specified System. String objects by calculating the value of the corresponding System. Char object in each String.
//
// Parameters:
// StrA:
// The first System. String.
//
// StrB:
// The second System. String.
//
// Return result:
// An integer that indicates the lexical relationship between two comparisons. The value condition is smaller than zero and less than strB. Zero strA and strB are equal. Greater than zero strA
// StrB.
Public static int CompareOrdinal (string strA, string strB );
//
// Summary:
// Calculate the value of the corresponding System. Char object in each substring of two specified System. String objects to compare the substrings.
//
// Parameters:
// StrA:
// The first System. String.
//
// IndexA:
// Start index of the strA neutron string.
//
// StrB:
// The second System. String.
//
// IndexB:
// Start index of strB neutron string.
//
// Length:
// The maximum number of characters in the substring to be compared.
//
// Return result:
// A 32-bit signed integer that indicates the lexical relationship between two comparisons. The value condition is smaller than that of the sub-string in strB. Zero substrings are equal, or
// The length is zero. The substring greater than zero in strA is greater than the substring in strB.
//
// Exception:
// System. ArgumentOutOfRangeException:
// IndexA is greater than strA. System. String. Length.-Or-indexB is greater than strB. System. String. Length.
//-Or-indexA, indexB, or length is negative.
Public static int CompareOrdinal (string strA, int indexA, string strB, int indexB, int length );