3

SQL Server データベースにデータ型の列があり、dateこれを挿入します1999-12-23。データベースで選択クエリを実行すると1999-12-23日付が表示されますが、データベースを c# winform アプリケーションに接続し、表示される日付を取得すると1999-12-23 00:00:00(つまり、日付と時刻が表示されます)。

これらは私が使用したコードです

テーブルの作成

CREATE TABLE Users.Personal
(
/*...Other Codes for the table this is the main problem*/
DateofReg date NOT NULL
)

クエリを選択

SELECT * FROM Users.Personal

(これにより、日付が として表示されます1999-12-23)

データベースへの接続

private void RetrievePersonalDetails()
{
    SqlConnection myConnection = new SqlConnection("server=AMESINLOLA;" +
        "Trusted_Connection=yes;" +
        "database=Crm_Db;");
    myConnection.Open();

    SqlCommand myCommand = myConnection.CreateCommand();
    myCommand.CommandText = "SELECT * FROM Users.Personal WHERE UniqueID='" + uniqueid + "'";
    myCommand.CommandType = CommandType.Text;

    SqlDataReader myReader = myCommand.ExecuteReader();

    if (myReader.Read())
    {
        //Other codes inserting to textbox but this is the main problem
        txtDor.Text = myReader["DateofReg"].ToString();
    }
    else
    {
        MessageBox.Show("Empty");
    }
    myConnection.Close();
    myReader.Close();
}

(これにより、日付が として表示されます1999-12-23 00:00:00)

アプリケーションでは日付が時間とともに表示されるのに、データベースではうまく表示されるのはなぜですか? また、日付のみを表示するにはどうすればよいですか?

4

6 に答える 6

2

SQL Server にはDATE時刻のない日付の型がありますが、.NET のコア基本クラス ライブラリにはそのようなものはありません。DateTimeそのため、代わりに時刻が真夜中に設定されたa が使用されます。

から日付だけを含む文字列を取得する方法はたくさんありますDateTimeが、はそれをとしてmyReader["DateofReg"]ボクシングするため、何かを行う場合は最初にキャストする必要があります。例えば、DateTimeobject

// Unbox the result by casting
DateTime dt = (DateTime) myReader["DateofReg"];

// Use a string formatter to get what you want
txtDor.Text = dt.ToString("d");

// or if you prefer, use this shortcut method
txtDor.Text = dt.ToShortDateString();

これは問題なく動作するはずですが、何らかの理由で単なる文字列やDateTime真夜中ではない純粋な「時刻のない日付」型が実際に必要な場合は、 Noda TimeライブラリのLocalDate型を使用できます。

于 2013-09-29T21:19:37.853 に答える