如何在C#中的DateTime类型中仅比较没有时间的日期,其中一个日期可以为空,我该怎么做?
DateTime val1;
DateTime? val2;
if (!val2.HasValue)
return false;
return val1.Date == val2.Value.Date;
You can use the Date
property of DateTime
object
Datetime x;
Datetime? y;
if (y != null && y.HasValue && x.Date == y.Value.Date)
{
//DoSomething
}
This uses short-circuit to avoid comparisons if nullable date is null, then uses the DateTime.Date property to determine equivalency.
bool Comparison(DateTime? nullableDate, DateTime aDate) {
if(nullableDate != null && aDate.Date == nullableDate.Value.Date) {
return true;
}
return false;
}
bool DatesMatch(DateTime referenceDate, DateTime? nullableDate)
{
return (nullableDate.HasValue) ?
referenceDate.Date == nullableDate.Value.Date :
false;
}
If you want a true comparison, you can use:
Datetime dateTime1
Datetime? dateTime2
if(dateTime2.Date != null)
dateTime1.Date.CompareTo(dateTime2.Date);
Hope it helps...
The only challenging aspect here is the fact that you want something which is both DateTime and nullable.
Here is the solution for standard DateTime: How to compare only Date without Time in DateTime types in C#?
if(dtOne.Date == dtTwo.Date)
For nullable, it's just a matter of choice. I would choose an extension method.
class Program
{
static void Main(string[] args)
{
var d1 = new DateTime(2000, 01, 01, 12, 24, 48);
DateTime? d2 = new DateTime(2000, 01, 01, 07, 29, 31);
Console.WriteLine((d1.Date == ((DateTime)d2).Date));
Console.WriteLine((d1.CompareDate(d2)));
Console.WriteLine((d1.CompareDate(null)));
Console.WriteLine("Press enter to continue...");
Console.ReadLine();
}
}
static class DateCompare
{
public static bool CompareDate(this DateTime dtOne, DateTime? dtTwo)
{
if (dtTwo == null) return false;
return (dtOne.Date == ((DateTime)dtTwo).Date);
}
}
You could create a method like the one below, following the similar return values as the .net framework comparisons, giving -1 when the left side is smallest, 0 for equal dates, and +1 for right side smallest:
private static int Compare(DateTime? firstDate, DateTime? secondDate)
{
if(!firstDate.HasValue && !secondDate.HasValue)
return 0;
if (!firstDate.HasValue)
return -1;
if (!secondDate.HasValue)
return 1;
else
return DateTime.Compare(firstDate.Value.Date, secondDate.Value.Date);
}
Of Course a nicer implementation would be to create an extension method for this.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.