简体   繁体   English

CDate有什么奇怪的行为?

[英]What a strange behavior of CDate?

I found that CDate function has a strange behavior in the following code : 我发现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());
            }


        }

I understand that if the value is bigger than 12, the CDate function will consider it as the 'Day' part of the date and the other part will be considered as the 'Month' part of the date. 我知道,如果该值大于12,则CDate函数会将其视为日期的“天”部分,而另一部分将视为日期的“月”部分。

source code can be downloaded from ( Link ). 可以从( Link )下载源代码。

What is the rule for that ? 这有什么规则?

why Microsoft did not explain this in the MSDN ? 为什么Microsoft没有在MSDN中对此进行解释?

Yes you are right. 是的,你是对的。 CDate tries to treat a month value greater than 12 as a day value. CDate尝试将大于12的月值视为日值。

You May try this. 您可以尝试一下。

private bool IsDate(String inputDate)
{
  DateTime dt;


  Return DateTime.TryParse(inputDate,out dt);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM