2011-12-28 81 views
0

我有一個日期變量startdt字符串變量hdnsdate比較在vb.net兩個日期它們是否相等或不

假設如果startdt具有形式的值2012/3/1hdnsdate具有形式03/01/2012的值。我怎麼能比較這兩個日期在vb.net相等。

if我的程序的條件我想做這個檢查。如果兩個日期匹配移出if循環,否則進入if循環。

E.g C#中的一個示例,究竟是我想要的。

if(startdt !=hdnsdate) 
{ 
//Do 
} 
else 
{ 
//Do this 
} 
+0

你的代碼示例是C#,但你這個標記用VB.NET - 這是什麼呢? – Oded 2011-12-28 10:31:26

+0

@Oded C#是一個示例,我想在vb.net中做到這一點 – Ishan 2011-12-28 10:36:05

+0

您的代碼示例應該真正反映標籤。這只是令人困惑。 – Oded 2011-12-28 10:51:55

回答

3

hdnsdate解析(字符串)日期類型使用解析,ParseExact方法和使用DateTime.CompareEqualsCompareTo方法。

字符串到日期

Dim enddate as Date 
Date.TryParse(hdnsdate, enddate) 

If startdt = enddate Then 
    'Do this 
Else 
    'Do this 
End If 

替代比較日期:

Dim result = DateTime.Compare(date1, date2) 
If result=0 Then 
    'Do this 
End If 
4

您需要將字符串解析爲DateTime然後比較兩者。

VB.NET

Dim parsed As DateTime = DateTime.Parse(hdnsdate) 

If startdt != parsed Then 

Else 

End If 

C#:

DateTime parsed = DateTime.Parse(hdnsdate); 

if(startdt != parsed) 
{ 
//Do 
} 
else 
{ 
//Do this 
} 

我建議看在DateTime定義的不同的解析方法,你可能需要使用standardcustom日期和時間格式字符串以確保字符串正確解析。

0

Dim result = DateTime.Compare(hdnsdate, date2) 
If result=0 Then 
    'Do this 
End If 
+1

你也可以參考這個鏈接https://msdn.microsoft.com/en-us/library/system.datetime.compare(v=vs.110).aspx – saggy 2016-12-30 10:19:46