C# DateTime Compare

Description

DateTime Compare compares two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance.

Syntax

DateTime.Compare has the following syntax.


public static int Compare(
  DateTime t1,
  DateTime t2
)

Parameters

DateTime.Compare has the following parameters.

  • t1 - The first object to compare.
  • t2 - The second object to compare.

Returns

DateTime.Compare method returns A signed number indicating the relative values of t1 and t2. Value Type Condition Less than zero t1 is earlier than t2. Zero t1 is the same as t2. Greater than zero t1 is later than t2.

Example

The following example demonstrates the Compare method.


using System;/*from w  w w  . j a v  a2s.  c  om*/

public class Example
{
   public static void Main()
   {
      DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
      DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0);
      int result = DateTime.Compare(date1, date2);

      if (result < 0)
         Console.WriteLine("is earlier than");
      else if (result == 0)
         Console.WriteLine("is the same time as");         
      else
         Console.WriteLine("is later than");
   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version