此方法用于比较两个DateTime实例,并返回一个整数,该整数指示第一个实例是否早于,相同或晚于第二个实例。
用法:
public static int Compare (DateTime t1, DateTime t2);
参数:
- t1:要比较的第一个对象。
- t2:要比较的第二个对象。
返回值:此方法返回一个带符号的数字,指示t1和t2的相对值。
Less than zero : If t1 is earlier than t2.
Zero : If t1 is the same as t2.
Greater than zero : If t1 is later than t2.
以下示例程序旨在说明DateTime.Compare(DateTime,DateTime)方法的用法:
示例1:
// C# program to demonstrate the
// DateTime.Compare(DateTime,
// DateTime) Method
using System;
class GFG {
// Main Method
public static void Main()
{
// creating object of DateTime
DateTime date1 = new DateTime(2010, 1,
1, 4, 0, 15);
// creating object of DateTime
DateTime date2 = new DateTime(2010, 1,
1, 4, 0, 14);
// comparing date1 and date2
// using Compare() method;
int value = DateTime.Compare(date1, date2);
// checking
if (value > 0)
Console.Write("date1 is later than date2. ");
else if (value < 0)
Console.Write("date1 is earlier than date2. ");
else
Console.Write("date1 is the same as date2. ");
}
}
输出:
date1 is later than date2.
示例2:
// C# program to demonstrate the
// DateTime.Compare(DateTime,
// DateTime) Method
using System;
class GFG {
// Main Method
public static void Main()
{
// calling check() method
check(new DateTime(2010, 1, 3, 4, 0, 15),
new DateTime(2010, 1, 4, 4, 0, 15));
check(new DateTime(2010, 1, 5, 4, 0, 15),
new DateTime(2010, 1, 4, 4, 0, 15));
check(new DateTime(2010, 1, 5, 4, 0, 15),
new DateTime(2010, 1, 5, 4, 0, 15));
}
public static void check(DateTime date1,
DateTime date2)
{
// comparing date1 and date2
// using Compare() method;
int value = DateTime.Compare(date1, date2);
// checking
if (value > 0)
Console.WriteLine(" {0:d} is later than {1:d}. ",
date1, date2);
else if (value < 0)
Console.WriteLine(" {0:d} is earlier than {1:d}. ",
date1, date2);
else
Console.WriteLine(" {0:d} is the same as {1:d}. ",
date1, date2);
}
}
输出:
01/03/2010 is earlier than 01/04/2010. 01/05/2010 is later than 01/04/2010. 01/05/2010 is the same as 01/05/2010.
参考:
相关用法
- C# Uri.IsBaseOf(Uri)用法及代码示例
- C# Random.Next()用法及代码示例
- C# Uri.ToString()用法及代码示例
- C# Uri.IsWellFormedOriginalString()用法及代码示例
- C# Uri.GetHashCode()用法及代码示例
- C# Math.Log()用法及代码示例
- C# Uri.FromHex()用法及代码示例
- C# Uri.IsHexDigit()用法及代码示例
- C# Queue.Contains()用法及代码示例
注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 DateTime.Compare() Method in C#。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。