2013-01-16 82 views
0

我发现CDate函数在下面的代码奇怪的行为:CDate有什么奇怪的行为?

private void button1_Click(object sender, EventArgs e) 
     { 
      OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;User ID=Admin;Data Source=" + Application.StartupPath + @"\db.mdb" + ";Persist Security Info=False"); 
      { 
       OleDbDataAdapter adapterA = new OleDbDataAdapter("SELECT CDate(#01/05/2013#) AS TheDate", connection); 
       DataTable dataTableA = new DataTable(); 
       adapterA.Fill(dataTableA); 
       DateTime dateTimeA = (DateTime)dataTableA.Rows[0]["TheDate"]; // get 1 
       MessageBox.Show(dateTimeA.Month.ToString()); 
      } //these to ensure that I did not use the variables in the next block /^-^\ . 


      { 
       OleDbDataAdapter adapterB = new OleDbDataAdapter("SELECT CDate(#13/05/2013#) AS TheDate", connection); 
       DataTable dataTableB = new DataTable(); 
       adapterB.Fill(dataTableB); 
       DateTime dateTimeB = (DateTime)dataTableB.Rows[0]["TheDate"]; // get 5 
       MessageBox.Show(dateTimeB.Month.ToString()); 
      } 


     } 

我明白,如果该值大于12越大,CDate功能将它视为日期的“日”部分,另一部分将被视为日期的'月'部分。

源代码可以从(Link)下载。

这是什么规则?

为什么微软没有在MSDN中解释这一点?

+2

也许这只是VB.NET和那个SQL之间的一个奇怪的巧合,但不要'#'分隔日期文字?所以'CDate'与它无关;日期文字会自动更改格式。 “无论什么都有效”:P – Ryan

+0

如果您需要CDate,请同意@minitech,使用字符串。此外,年,月,日可以节省语言环境问题。 – Fionnuala

回答

0

是的你是对的。 CDate会尝试将大于12的月份值视为日值。

你可以试试这个。

private bool IsDate(String inputDate) 
{ 
    DateTime dt; 


    Return DateTime.TryParse(inputDate,out dt); 

}