DateTime.CompareTo DateTime.CompareTo DateTime.CompareTo DateTime.CompareTo Method

Definición

Compara el valor de esta instancia con un valor de DateTime especificado e indica si esta instancia es anterior, igual o posterior al valor de DateTime especificado.Compares the value of this instance to a specified DateTime value and indicates whether this instance is earlier than, the same as, or later than the specified DateTime value.

Sobrecargas

CompareTo(DateTime) CompareTo(DateTime) CompareTo(DateTime) CompareTo(DateTime)

Compara el valor de esta instancia con un valor de DateTime especificado y devuelve un entero que indica si esta instancia es anterior, igual o posterior al valor de DateTime especificado.Compares the value of this instance to a specified DateTime value and returns an integer that indicates whether this instance is earlier than, the same as, or later than the specified DateTime value.

CompareTo(Object) CompareTo(Object) CompareTo(Object) CompareTo(Object)

Compara el valor de esta instancia con un objeto especificado que contiene un valor de DateTime especificado y devuelve un entero que indica si esta instancia es anterior, igual o posterior al valor de DateTime especificado.Compares the value of this instance to a specified object that contains a specified DateTime value, and returns an integer that indicates whether this instance is earlier than, the same as, or later than the specified DateTime value.

Comentarios

Las dos sobrecargas de los CompareTo método devuelva un número con signo que indica el valor relativo de esta instancia y el value argumento, tal como se muestra en la tabla siguiente.The two overloads of the CompareTo method return a signed number that indicates the relative value of this instance and the value argument, as shown in the following table.

ValorValue DescripciónDescription
Menor que ceroLess than zero Esta instancia es anterior a value.This instance is earlier than value.
CeroZero Esta instancia es la misma que value.This instance is the same as value.
Mayor que ceroGreater than zero Esta instancia es posterior a value.This instance is later than value.

CompareTo(DateTime) CompareTo(DateTime) CompareTo(DateTime) CompareTo(DateTime)

Compara el valor de esta instancia con un valor de DateTime especificado y devuelve un entero que indica si esta instancia es anterior, igual o posterior al valor de DateTime especificado.Compares the value of this instance to a specified DateTime value and returns an integer that indicates whether this instance is earlier than, the same as, or later than the specified DateTime value.

public:
 virtual int CompareTo(DateTime value);
public int CompareTo (DateTime value);
abstract member CompareTo : DateTime -> int
override this.CompareTo : DateTime -> int
Public Function CompareTo (value As DateTime) As Integer

Parámetros

value
DateTime DateTime DateTime DateTime

Objeto que se va a comparar con la actual instancia.The object to compare to the current instance.

Devoluciones

Número con signo que indica los valores relativos de esta instancia y del parámetro value.A signed number indicating the relative values of this instance and the value parameter.

ValorValue DescripciónDescription
Menor que ceroLess than zero Esta instancia es anterior a value.This instance is earlier than value.
CeroZero Esta instancia es la misma que value.This instance is the same as value.
Mayor que ceroGreater than zero Esta instancia es posterior a value.This instance is later than value.

Implementaciones

Ejemplos

El ejemplo siguiente crea tres DateTime objetos, uno que representa la actual fecha, otro que representa la fecha un año anterior y un tercero que representa la fecha un año en el futuro.The following example instantiates three DateTime objects, one that represents today's date, another that represents the date one year previously, and a third that represents the date one year in the future. A continuación, llama el CompareTo(DateTime) método y muestra el resultado de la comparación.It then calls the CompareTo(DateTime) method and displays the result of the comparison.

using System;

public class DateTimeComparison
{
   private enum DateComparisonResult
   {
      Earlier = -1,
      Later = 1,
      TheSame = 0
   };

   public static void Main()
   {
      DateTime thisDate = DateTime.Today;


      // Define two DateTime objects for today's date 
      // next year and last year		
      DateTime thisDateNextYear, thisDateLastYear;

      // Call AddYears instance method to add/substract 1 year
      thisDateNextYear = thisDate.AddYears(1);
      thisDateLastYear = thisDate.AddYears(-1);   

      // Compare dates
      //
      DateComparisonResult comparison;
      // Compare today to last year
      comparison = (DateComparisonResult) thisDate.CompareTo(thisDateLastYear);
      Console.WriteLine("CompareTo method returns {0}: {1:d} is {2} than {3:d}", 
                        (int) comparison, thisDate, comparison.ToString().ToLower(), 
                        thisDateLastYear);
      
      // Compare today to next year
      comparison = (DateComparisonResult) thisDate.CompareTo(thisDateNextYear);
      Console.WriteLine("CompareTo method returns {0}: {1:d} is {2} than {3:d}", 
                        (int) comparison, thisDate, comparison.ToString().ToLower(), 
                        thisDateNextYear);
   }
}
//
// If run on October 20, 2006, the example produces the following output:
//    CompareTo method returns 1: 10/20/2006 is later than 10/20/2005
//    CompareTo method returns -1: 10/20/2006 is earlier than 10/20/2007
Option Strict On

Module DateTimeComparison
   Private Enum DateComparisonResult
      Earlier = -1
      Later = 1
      TheSame = 0
   End Enum
   
   Public Sub Main()

      Dim thisDate As Date = Date.Today

      ' Define two DateTime objects for today's date 
      ' next year and last year		
      Dim thisDateNextYear, thisDateLastYear As Date

      ' Call AddYears instance method to add/substract 1 year
      thisDateNextYear = thisDate.AddYears(1)
      thisDateLastYear = thisDate.AddYears(-1)   

       
      ' Compare dates
      '
      Dim comparison As DateComparisonResult
      ' Compare today to last year
      comparison = CType(thisDate.CompareTo(thisDateLastYear), DateComparisonResult)
      Console.WriteLine("CompareTo method returns {0}: {1:d} is {2} than {3:d}", _ 
                        CInt(comparison), thisDate, comparison.ToString().ToLower(), _ 
                        thisDateLastYear)
      
      ' Compare today to next year
      comparison = CType(thisDate.CompareTo(thisDateNextYear), DateComparisonResult)
      Console.WriteLine("CompareTo method returns {0}: {1:d} is {2} than {3:d}", _
                        CInt(comparison), thisDate, comparison.ToString().ToLower(), _
                        thisDateNextYear)
   End Sub
End Module
'
' If run on October 20, 2006, the example produces the following output:
'    CompareTo method returns 1: 10/20/2006 is later than 10/20/2005
'    CompareTo method returns -1: 10/20/2006 is earlier than 10/20/2007

Comentarios

Para determinar la relación de la instancia actual a value, el CompareTo método compara la Ticks propiedad de la instancia actual y value pero omite su Kind propiedad.To determine the relationship of the current instance to value, the CompareTo method compares the Ticks property of the current instance and value but ignores their Kind property. Antes de comparar DateTime objetos, asegúrese de que los objetos representan horas en la misma zona horaria.Before comparing DateTime objects, make sure that the objects represent times in the same time zone. Puede hacerlo comparando los valores de sus Kind propiedades.You can do this by comparing the values of their Kind properties.

Este método implementa el System.IComparable<T> interfaz y realiza un poco mejor que el DateTime.CompareTo(Object) sobrecarga del método porque no tiene que convertir el value parámetro a un objeto.This method implements the System.IComparable<T> interface and performs slightly better than the DateTime.CompareTo(Object) method overload because it does not have to convert the value parameter to an object.

Consulte también:

CompareTo(Object) CompareTo(Object) CompareTo(Object) CompareTo(Object)

Compara el valor de esta instancia con un objeto especificado que contiene un valor de DateTime especificado y devuelve un entero que indica si esta instancia es anterior, igual o posterior al valor de DateTime especificado.Compares the value of this instance to a specified object that contains a specified DateTime value, and returns an integer that indicates whether this instance is earlier than, the same as, or later than the specified DateTime value.

public:
 virtual int CompareTo(System::Object ^ value);
public int CompareTo (object value);
abstract member CompareTo : obj -> int
override this.CompareTo : obj -> int
Public Function CompareTo (value As Object) As Integer

Parámetros

value
Object Object Object Object

Objeto al que se ha aplicado la conversión boxing y que se va a comparar o null.A boxed object to compare, or null.

Devoluciones

Número con signo que indica los valores relativos de esta instancia y value.A signed number indicating the relative values of this instance and value.

ValorValue DescripciónDescription
Menor que ceroLess than zero Esta instancia es anterior a value.This instance is earlier than value.
CeroZero Esta instancia es la misma que value.This instance is the same as value.
Mayor que ceroGreater than zero Esta instancia es posterior a value o bien value es null.This instance is later than value, or value is null.

Implementaciones

Excepciones

Ejemplos

En el ejemplo siguiente se muestra el CompareTo método.The following example demonstrates the CompareTo method.

using namespace System;
void main()
{
   

   System::DateTime theDay(System::DateTime::Today.Year,7,28);
   int compareValue;
   try
   {
      compareValue = theDay.CompareTo( System::DateTime::Today );
   }
   catch ( ArgumentException^ ) 
   {
      System::Console::WriteLine( "Value is not a DateTime" );
      return;
   }

   if ( compareValue < 0 )
   {
      System::Console::WriteLine( "{0:d} is in the past.", theDay );
   }
   else
   if ( compareValue == 0 )
   {
      System::Console::WriteLine( "{0:d} is today!", theDay );
   }
   else
   // compareValue > 0 
   {
      System::Console::WriteLine( "{0:d} has not come yet.", theDay );
   }
}
System.DateTime theDay = new System.DateTime(System.DateTime.Today.Year, 7, 28);
int compareValue;

try 
{
    compareValue = theDay.CompareTo(DateTime.Today);
} 
catch (ArgumentException) 
{
   Console.WriteLine("Value is not a DateTime");
   return;
}

if (compareValue < 0) 
   System.Console.WriteLine("{0:d} is in the past.", theDay);
else if (compareValue == 0) 
   System.Console.WriteLine("{0:d} is today!", theDay);
else // compareValue > 0
   System.Console.WriteLine("{0:d} has not come yet.", theDay);
Dim thDay As New System.DateTime(System.DateTime.Today.Year, 7, 28)

Dim compareValue As Integer
Try
   compareValue = thDay.CompareTo(System.DateTime.Today)
Catch exp As ArgumentException
   System.Console.WriteLine("Value is not a DateTime")
End Try

If compareValue < 0 Then
   System.Console.WriteLine("{0:d} is in the past.", thDay)
ElseIf compareValue = 0 Then
   System.Console.WriteLine("{0:d} is today!", thDay)
Else   ' compareValue >= 1 
   System.Console.WriteLine("{0:d} has not come yet.", thDay)
End If

Comentarios

Para determinar la relación de la instancia actual a value, el CompareTo método compara la Ticks propiedad de la instancia actual y value pero omite su Kind propiedad.To determine the relationship of the current instance to value, the CompareTo method compares the Ticks property of the current instance and value but ignores their Kind property. Antes de comparar DateTime objetos, asegúrese de que los objetos representan horas en la misma zona horaria.Before comparing DateTime objects, make sure that the objects represent times in the same time zone. Puede hacerlo comparando los valores de sus Kind propiedades.You can do this by comparing the values of their Kind properties.

Cualquier instancia de DateTime, independientemente de su valor, se considera mayor null.Any instance of DateTime, regardless of its value, is considered greater than null.

Consulte también:

Se aplica a