How to format datetime to only specific DATE format in datatable
Solution 1
Do not try to change the 'format' of a datetime column in a datatable.
Simply a DateTime has no format by itself.
It is the tool that you use to display the date that has the task to present it in a human readable format, whatever this format is.
In other words. It is the DataGridView that must carry out this task.
You just need to set
dataGridView1.Columns[0].DefaultCellStyle.Format = "dd/MM/yyyy";
(Assuming that the grid column at index zero is your date column)
Solution 2
Place the custom format in the output ToString()
, not the input.
foreach (DataRow dr in ltdgv.Rows)
{
dr["DATE"] = DateTime.Parse((dr["DATE"].ToString())).ToString("dd/MM/yyyy");
}
phapha pha
Updated on May 15, 2021Comments
-
phapha pha almost 3 years
In my datagridview1, the DATE column show format "MM/dd/yyyy hh:mm:ss"
Then I use this code.
I use a function to fill a datagridview like this
public void load_table() { DataTable ltdgv = getLoad_table(); //the getLoad_table() function return a datatable type and store it to ltdgv foreach (DataRow dr in ltdgv.Rows) { dr["DATE"] = DateTime.Parse((dr["DATE"].ToString())).ToShortDateString(); } dataGridView1.DataSource = ltdgv; }
but the DATE column still showing format MM/dd/yyyy [ex: 11/27/2016]
but I want to change it to dd/MM/yyyy or 27/11/2016
I tried to change it into =
dr["DATE"] = DateTime.Parse((dr["DATE"].ToString("dd/MM/yyyy"))).ToShortDateString(); // I fill a parameter to the .ToString()
But I now get a "syntax error".
So, how to fix this?