How to set format datetime in new datacolumn

Viewed 4940
dt.Columns.Add(new DataColumn("BeginDate", typeof(DateTime)));

dr["BeginDate"] = Ds.Tables["tDocument"].Rows[i]["vc01"].ToString();

How do I set the datetime format to "dd/MM/yyyy"? Right now, it looks like this:

14/09/2018 00:00:00
4 Answers

Here is a demo:

DataTable dt = new DataTable();
dt.Columns.Add("BeginDate", typeof(string));

DataRow dr = dt.NewRow();
dr["BeginDate"] = DateTime.Now.ToString("dd/MM/yyyy");
dt.Rows.Add(dr);

foreach (DataRow item in dt.Rows)
{
    Console.WriteLine(item["BeginDate"]);
}

For your case,please try following code:

dt.Columns.Add(new DataColumn("BeginDate", typeof(string)));

dr["BeginDate"] = Ds.Tables["tDocument"].Rows[i]["vc01"].ToString("dd/MM/yyyy");

If you want to sort the datetime column in a datagridview, you just need to change the column format like bellow:

dataGrid.Columns["colName"].DefaultCellStyle.Format = "dd/MM/yyyy";

If you use datagridview, then you need to format its column, not the datasource. Otherwise you won't be able to sort column by date. Datagridview will allow you to put anything if you allow it to edit data.

var row = dataTable1.NewRow();
row["BeginDate"] = DateTime.Now;
dataTable1.Rows.Add(row);
dataGridView1.Columns["beginDateDataGridViewTextBoxColumn"].DefaultCellStyle.Format = "dd/MM/yyyy";

beginDateDataGridViewTextBoxColumn is the name of the dataGridView column which was generated for "BeginDate" column.

if you use combobox, then format it using FormatString:

comboBox1.FormatString = "dd/MM/yyyy";

The / character in date/time format strings stands for "whatever the date separator of the format provider is". Since you do not supply a format provider Thread.CurrentCulture is used, and in your case the current culture uses . as the date separator. If you want to use a literal slash, place it inside single quotes:

Ds.Tables["tDocument"].Rows[i]["vc01"].ToString("dd'/'MM'/'yyyy");

Alternatively, you could specify a format provider where the date separator is /:

Ds.Tables["tDocument"].Rows[i]["vc01"].ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

Try to do Like this

 dt.Columns.Add(new DataColumn("BeginDate", typeof(String)));
 dr["BeginDate"] = Ds.Tables["tDocument"].Rows[i]["vc01"].ToString("dd/MM/yyyy");
Related