I have a column with a date datatype in my sql-server database and I insert this into it 1999-12-23. When i run the select query in my database is shows the date as 1999-12-23 but when i connect the database to my c# winform application and retrieve the date it displays as 1999-12-23 00:00:00 (i.e it displays date and time).
These are the codes i used
Create Table
CREATE TABLE Users.Personal
(
/*...Other Codes for the table this is the main problem*/
DateofReg date NOT NULL
)
Select query
SELECT * FROM Users.Personal
(This displays the date as 1999-12-23)
Connection to Database
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();
}
(This displays the date as 1999-12-23 00:00:00)
Why is the date displaying with time in the application but displaying well in the database and what can i do to display only date?
myReader["DateofRef"] seems to return a DateTime object. This internally stores the ticks of your date value (which includes time and milliseconds etc).
ToString applies a default formatting for your DateTime object.
you can also use
DateTime.Now.ToShortDateString() which will print only year, month and day.
The format though will depend on the current culture (Thread.CurrentThread.CurrentCulture), ToStrin also takes a parameter called IFormatProvider, this can be set to any culture you want to specify how the date string should look like by using CultureInfo...
You can change the formatting by passing in the format to the ToString method.
Lots of examples can be found here http://msdn.microsoft.com/en-US/library/zdtaw1bw(v=vs.110).aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With