I'm developing a c# program and i need to store some date in a sql server database. In my able I have a column type date where i need to store year, month and day. So I convert the date in c# program from dd/mm/yyyy (italian format) to yyyy-mm-dd and the I insert it in the database. When I go to read the data from the table and I display it inside the textbox i see the date followed by hours:minutes:seconds. Why? In my database I only store yyyy-mm-dd (I check it in sql management studio) and in c# program i use a string type to save the date in a property of an object:
public string data_fattura
{
get { return checkStringGet(_data_fattura); }
set { _data_fattura = checkDataSet(value); }
}
private string checkDataSet(string data)
{
string[] tmp = data.Split('/');
return tmp[2] + "-" + tmp[1] + "-" + tmp[0];
}
private string checkStringGet(string data)
{
string[] tmp = data.Split('-');
return tmp[2] + "/" + tmp[1] + "/" + tmp[0];
}
Don't convert it to a string at all where you don't need to.
Convert from the string you get from the user using DateTime.ParseExact
, and then keep it as a DateTime
. Use that as a parameter in parameterized SQL to insert it into the database. The database won't be storing it in a text format anyway.
When you fetch it from the database, you'll also have a DateTime
. (You can just cast the value from the reader - you don't need to go anywhere near a text representation when fetching from the database.) When you want to display that to the user, format it appropriately (using ToString
).
Basically, keep the value as a DateTime
(or DateTimeOffset
, potentially) for as much of the time as possible... as early as you can when you get the text from the user (ideally, use a control which is date/time aware so you don't even need it then) and as late as you can when you present it back to the user.
As for the time appearing - it's not entirely clear where it was appearing. If you only want a date, you should have a date
column rather than datetime
. You'll still fetch the value back as a DateTime
.NET value, but when you convert that to a string, just use a format which is date-only. .NET doesn't have a type which is "just a date" (unfortunately, IMO).