O.Austin
O.Austin

Reputation: 13

Format a date to dd/MM/yyyy in a listView from a database

I am trying to format a date in a list view so that only the date appears in the format dd/MM/yyyy and not the time. I have tried to only return the date in the SQL but the time appears as 00:00 etc. Also, I have tried to format the string using .ToString("dd/MM/yyyy").

     private void Home_Load(object sender, EventArgs e)
    {
        string str = "Server=DESKTOP-NB0VA19\\SQLEXPRESS;Database=database_name; Integrated Security=True;";
        SqlConnection conn = new SqlConnection(str);
        conn.Open();
        DataTable dt = new DataTable();
        SqlDataAdapter ada = new SqlDataAdapter("SELECT job_type, job_number, CONVERT(date,due_date) AS 'due_date', job_description FROM job", conn);
        ada.Fill(dt);

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            DataRow dr = dt.Rows[i];
            ListViewItem listitem = new ListViewItem(dr["job_type"].ToString());
            listitem.SubItems.Add(dr["job_number"].ToString());

            listitem.SubItems.Add(dr["due_date"].ToString());

            listitem.SubItems.Add(dr["job_description"].ToString());
            listView1.Items.Add(listitem);
        }

Upvotes: 1

Views: 3337

Answers (1)

You need to parse to DateTime first:

var dt = DateTime.Parse(dr["due_date"].ToString());
listitem.SubItems.Add(dt.ToString("dd/MM/yyyy");

Or, if it's already a DateTime:

var dt = dr.Field<DateTime>("due_date");
listitem.SubItems.Add(dt.ToString("dd/MM/yyyy");

Upvotes: 3

Related Questions