Convert DateTime in DataRow to a formatted date string

前端 未结 2 1178
星月不相逢
星月不相逢 2020-12-21 21:47

I\'m hoping that there is something I am not seeing clearly, but to simplify, I have the below code

foreach (DataRow row in dt.Rows)
{
  row[\"StartOn\"] = C         


        
2条回答
  •  太阳男子
    2020-12-21 22:22

    What is dt.Columns["StartOn"]. I suspect this is DateTime. Let me break down your single line of code into 2 lines.

    string s = Convert.ToDateTime(row["StartOn"].ToString()).ToString("MMM dd").ToString();
    row["StartOn"] = s;
    

    In line 1, you are converting a DateTime object to a string object. But on line 2, you are implicitly converting your string to a DateTime

    var dt = new DataTable();
    dt.Columns.Add("StartOn", typeof(DateTime));
    dt.Rows.Add(DateTime.Today);
    
    foreach (DataRow row in dt.Rows) {
        var data = Convert.ToDateTime(row["StartOn"].ToString()).ToString("MMM dd").ToString();
        Console.WriteLine($"Type of stored data is: {data.GetType()}");
        row["StartOn"] = data;
    }
    
    // fetch the data
    var fetchedData = dt.Rows[0][0];
    Console.WriteLine($"Type of Fetched Data is: {fetchedData.GetType()}");
    

    BTW, you can use the below line to do the conversion

    ((DateTime)row["StartOn"]).ToString("MMM dd");
    

提交回复
热议问题