假设我们有
DateTime t1 = DateTime.Parse("2012/12/12 15:00:00.000");
和
DateTime t2 = DateTime.Parse("2012/12/12 15:03:00.000");
如何在 C# 中比较它并说出哪个时间“晚于”?
, <
, <=
, >
,运算>=
符==
都直接作用于DateTime
和TimeSpan
对象。所以像这样的工作:
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
}
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
按照其他人的建议使用。如果你需要一些不那么细粒度的东西,你也可以使用Hour
andMinute
属性。
请参阅这些示例,这些示例解释了 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);