0

Why the following datatable contains datetime although the expected result from my SQL query is Date ?

public static DataTable CheckCalcDateToSend(int month, int year, int camp)
{
    DataTable dt = new DataTable();

    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ss"].ToString()))
    {
        StringBuilder Query = new StringBuilder();
        Query.Append(" SELECT CONVERT(date, to_date) AS to_date FROM CalcAttend  ");
        Query.Append(" WHERE month = @month AND year = @year");
        Query.Append(" AND camp = @camp AND emp_num = 0 ORDER BY calc_date");


        using (SqlCommand cmd = new SqlCommand(Query.ToString(), con))
        {
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@month", SqlDbType.Int).Value = month;
            cmd.Parameters.AddWithValue("@year", SqlDbType.Int).Value = year;
            cmd.Parameters.AddWithValue("@camp", SqlDbType.Int).Value = camp;
            con.Open();
            using (var dataReader = cmd.ExecuteReader())
            {
                dt.Load(dataReader);
            }
        }

    }
    return dt;
}
INDIA IT TECH
  • 1,902
  • 4
  • 12
  • 25
Anyname Donotcare
  • 11,113
  • 66
  • 219
  • 392
  • Dates in sql server still have a time value but the time is always exactly midnight. – Sean Lange Apr 04 '16 at 16:34
  • @SeanLange : then what should i do to return just a date ? My dropdownlist source have to be just list of dates – Anyname Donotcare Apr 04 '16 at 16:36
  • Not really sure what you mean. – Sean Lange Apr 04 '16 at 16:39
  • @SeanLange : I mean , I have a Drop Down List whose data source is that data table and have to be a date not a date time – Anyname Donotcare Apr 04 '16 at 16:40
  • Are you using an [`asp:DropDownList`](https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist%28v=vs.110%29.aspx)? If so, you can set the `DataTextFormatString` property to format the date times to just output the dates. – petelids Apr 04 '16 at 16:42
  • Missing 1 rep for comments... have you looked at [this](http://stackoverflow.com/a/4849412/5552144) post? – LuqJensen Apr 04 '16 at 16:46
  • 1
    There is no Date datatype. It is System.DateTime, that is why it is getting converted into DateTime. You will have to remove the Time part before binding it to the dropdownlist. – vabii Apr 04 '16 at 16:46
  • Why not convert your datetime to varchar in select? – Tony Dong Apr 04 '16 at 17:15

1 Answers1

1

In .Net, "Date" type does not exist. Default is "DateTime" type. "Date" property in "DateTime" variable will give date component. Alternatively, You can try to use DataTextFormatString for dropdownlist binding.

Refer this post Date in dropdownlist

Community
  • 1
  • 1
Babu Ashok
  • 26
  • 1