[英]Compare nullable datetime objects
我有兩個可為空的日期時間對象,我想比較兩者。 最好的方法是什么?
我已經嘗試過:
DateTime.Compare(birthDate, hireDate);
這給出了一個錯誤,也許它需要System.DateTime
類型的日期,而我有 Nullable 日期時間。
我也試過:
birthDate > hiredate...
但結果並不如預期......有什么建議嗎?
要比較兩個Nullable<T>
對象,請使用Nullable.Compare<T>
例如:
bool result = Nullable.Compare(birthDate, hireDate) > 0;
你也可以這樣做:
使用 Nullable DateTime 的 Value 屬性。 (記得檢查兩個對象是否都有一些值)
if ((birthDate.HasValue && hireDate.HasValue)
&& DateTime.Compare(birthDate.Value, hireDate.Value) > 0)
{
}
如果兩個值都相同 DateTime.Compare 將返回0
就像是
DateTime? birthDate = new DateTime(2000, 1, 1);
DateTime? hireDate = new DateTime(2013, 1, 1);
if ((birthDate.HasValue && hireDate.HasValue)
&& DateTime.Compare(birthDate.Value, hireDate.Value) > 0)
{
}
Nullable.Equals指示兩個指定的 Nullable(Of T) 對象是否相等。
嘗試:
if(birthDate.Equals(hireDate))
最好的方法是: Nullable.Compare 方法
Nullable.Compare(birthDate, hireDate));
如果您希望將null
值視為default(DateTime)
您可以執行以下操作:
public class NullableDateTimeComparer : IComparer<DateTime?>
{
public int Compare(DateTime? x, DateTime? y)
{
return x.GetValueOrDefault().CompareTo(y.GetValueOrDefault());
}
}
並像這樣使用它
var myComparer = new NullableDateTimeComparer();
myComparer.Compare(left, right);
另一種方法是為值可比較的Nullable
類型創建一個擴展方法
public static class NullableComparableExtensions
{
public static int CompareTo<T>(this T? left, T? right)
where T : struct, IComparable<T>
{
return left.GetValueOrDefault().CompareTo(right.GetValueOrDefault());
}
}
你會在哪里使用它
DateTime? left = null, right = DateTime.Now;
left.CompareTo(right);
使用Nullable.Compare<T>
方法。 像這樣:
var equal = Nullable.Compare<DateTime>(birthDate, hireDate);
正如@Vishal 所說,只需使用Nullable<T>
重寫Equals方法。 它是這樣實現的:
public override bool Equals(object other)
{
if (!this.HasValue)
return (other == null);
if (other == null)
return false;
return this.value.Equals(other);
}
如果兩個可為空的結構都沒有值,或者它們的值相等,則返回true
。 所以,只需使用
birthDate.Equals(hireDate)
嘗試
birthDate.Equals(hireDate)
並在比較后做你的事情。
或者,使用
object.equals(birthDate,hireDate)
我認為您可以按以下方式使用該條件
birthdate.GetValueOrDefault(DateTime.MinValue) > hireddate.GetValueOrDefault(DateTime.MinValue)
您可以編寫一個通用方法來計算任何類型的 Min 或 Max,如下所示:
public static T Max<T>(T FirstArgument, T SecondArgument) {
if (Comparer<T>.Default.Compare(FirstArgument, SecondArgument) > 0)
return FirstArgument;
return SecondArgument;
}
然后使用如下:
var result = new[]{datetime1, datetime2, datetime3}.Max();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.