Convert DateTime in DataRow to a formatted date string

微笑、不失礼 提交于 2019-12-12 00:48:53

问题


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"] = Convert.ToDateTime(row["StartOn"].ToString()).ToString("MMM dd").ToString();
}

If I run the below code I get “Aug 09”

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

If I look to see what is in row[“StartOn”] after this change it contains “8/9/2016 12:00:00 AM”

I'm unable to format my DataRow to an "MMM dd" format


回答1:


StartOn is apparently a DateTime type. DateTime types do NOT have a format. They are an object that specifies year, month, date, and time (among other things). All you are doing in your conversions is stripping out the time so that the new datetime has a time of 12:00 am.




回答2:


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");


来源:https://stackoverflow.com/questions/39046827/convert-datetime-in-datarow-to-a-formatted-date-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!