简体   繁体   中英

What a strange behavior of CDate?

I found that CDate function has a strange behavior in the following code :

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.

source code can be downloaded from ( Link ).

What is the rule for that ?

why Microsoft did not explain this in the MSDN ?

Yes you are right. CDate tries to treat a month value greater than 12 as a day value.

You May try this.

private bool IsDate(String inputDate)
{
  DateTime dt;


  Return DateTime.TryParse(inputDate,out dt);

}

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.

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