Reputation: 59
When I get data from Mysql table the datetime column 2017-09-19 16:14:47
will automatically convert into its own format like 9/19/2017 3:45:50 PM
. It happens when I'm getting data into DataTable
and convert into string as follows:
DataTable update;
localdb.MysqlQuery(queryUpdate);
update = localdb.QueryEx();
if (update.Rows.Count > 0)
{
onlinedb = new DataAccessOnline();
foreach (DataRow row in update.Rows)
{
row["added"].ToString(); //9/19/2017 3:45:50 PM
but I need get this value as it is in TABLE column 2017-09-19 16:14:47
how can I do that ?
Upvotes: 1
Views: 2390
Reputation: 4284
First you need to convert the data you get from the DB into a DateTime object using the Convert.ToDateTime method. Then you can specify the format you want on the DateTime.toString method.
It would look something like this:
DateTime added = Convert.ToDateTime(row["added"].ToString());
string formatted = added.toString("yyyy-MM-dd HH:mm:ss");
Upvotes: 3
Reputation: 4475
You can format it in your server side query as string.
mySql is giving data to C# as datetime type. C# has slightly different format of interpreting and presenting datetime type value to you. Ultimately, data will work like a datetime field anyways.
If you bring it like a formatted string, you would need to convert it to datetime in C# to make it function like a datetime. On the other hand, if you want it to be converted in C# for presentation purposes, do it in C#, not while bringing data because then it would be a string, not datetime.
You can see more .ToString() conversion details here.
Default format you need is "u", but you can provide your own format string like this one.
string dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
Upvotes: 2