44

假设我们有

DateTime t1 = DateTime.Parse("2012/12/12 15:00:00.000");

DateTime t2 = DateTime.Parse("2012/12/12 15:03:00.000");

如何在 C# 中比较它并说出哪个时间“晚于”?

4

4 回答 4

96

您可以使用TimeOfDay属性并对其使用Compare

TimeSpan.Compare(t1.TimeOfDay, t2.TimeOfDay)

根据文档:

-1  if  t1 is shorter than t2.
0   if  t1 is equal to t2.
1   if  t1 is longer than t2.
于 2012-04-24T00:34:01.667 回答
31

, <, <=, >,运算>===都直接作用于DateTimeTimeSpan对象。所以像这样的工作:

DateTime t1 = DateTime.Parse("2012/12/12 15:00:00.000");
DateTime t2 = DateTime.Parse("2012/12/12 15:03:00.000");

if(t1.TimeOfDay > t2.TimeOfDay) {
    //something
}
else {
    //something else
}
于 2012-04-24T00:33:32.620 回答
5

使用方法DateTime.Compare

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);
string relationship;

if (result < 0)
   relationship = "is earlier than";
else if (result == 0)
   relationship = "is the same time as";         
else
   relationship = "is later than";

Console.WriteLine("{0} {1} {2}", date1, relationship, date2);

编辑:如果您只想比较时间,而忽略日期,您可以TimeOfDay按照其他人的建议使用。如果你需要一些不那么细粒度的东西,你也可以使用HourandMinute属性。

于 2012-04-24T00:32:11.807 回答
1

请参阅这些示例,这些示例解释了 C# 中的时区转换。

var startTime = new System.TimeSpan(23,0,0);
var endTime = new System.TimeSpan(02,0,0);

var startDateTime = new DateTime(DateTime.UtcNow.Date.Year, DateTime.UtcNow.Date.Month, DateTime.UtcNow.Date.Day, startTime.Hours, startTime.Minutes, startTime.Seconds);
var endDateTime = new DateTime(DateTime.UtcNow.Date.Year, DateTime.UtcNow.Date.Month, DateTime.UtcNow.Date.Day, endTime.Hours, endTime.Minutes, endTime.Seconds);

var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
var startConvertedTime = TimeZoneInfo.ConvertTimeFromUtc(startDateTime, cetTimeZone);
var endConvertedTime = TimeZoneInfo.ConvertTimeFromUtc(endDateTime, cetTimeZone);

Console.WriteLine(startConvertedTime.TimeOfDay);
Console.WriteLine(endConvertedTime.TimeOfDay);

var currentTime = new TimeSpan(03,0,0);
Console.WriteLine(currentTime);

Console.WriteLine(currentTime >= startConvertedTime.TimeOfDay && currentTime <= endConvertedTime.TimeOfDay);
于 2021-12-15T08:05:50.287 回答