Unable to convert MySQL date/time value to System.DateTime

柔情痞子 提交于 2019-11-28 21:34:36

The problem in the format, actually mysql have a different format (yyyy-mm-dd) for the date/time data type and to solve this problem use the mysql connector library for .net from here http://dev.mysql.com/downloads/connector/net/ it will give other data type for the date/time called MysqlDateTime

or you can format the date/time data in your sql statement using DATE_FORMAT(date,format) you can get more details from here http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format

but i don't recommend this because you will loose the power of date/time data type (for example you can't compare) because now you will convert it to string but i think it will be useful in the reports

levefdsa
MySqlConnection connect = new MySqlConnection("server=localhost; database=luttop; user=root; password=1234; pooling = false; convert zero datetime=True");

Adding convert zero datetime=True to the connection string will automatically convert 0000-00-00 Date values to DateTime.MinValue().

that's SOLVED

Adding "convert zero datetime=True" to the connection string solved my problem.

<connectionStrings>   <add name="MyContext" connectionString="Datasource=localhost;Database=MyAppDb;Uid=root;Pwd=root;CHARSET=utf8;convert zero datetime=True" providerName="MySql.Data.MySqlClient" /> </connectionStrings>

Regards PS

user693858

I solved my problem by setting the column's default value as null data rather than using 0000-00-00 00:00:00:

update table set date = null

It could be outside the range of a DateTime object. I've seen that a couple of times. Try changing the sql to return the current date instead of your column and see if it comes through ok.

You need to do the simple change with the connection string you added for MySql database. i.e CONVERT ZERO DATETIME = TRUE

<add name="NAMEOFYOURCONNECTIONSTRING" connectionString="server's HOSTNAMEorIP(i.e Localhost or IP address);user id=USER_ID(i.e User ID for login Database);Pwd=PASSWORD(i.e User Password for login Database);persistsecurityinfo=True;database=NAMEOFDATABASE;Convert Zero Datetime=True" providerName="MySql.Data.MySqlClient"/>
Leacam

This worked for me:

SELECT 
    IF(tb.Date1 = '0000-00-00 00:00:00', NULL, tb.Date1) AS ValidDate
FROM MyTable AS tb

One thing who works too is changing your reader action. I was having this problem when I wrote

string myvar = reader.GetString(0);

Then I used to write this

object myvar = reader.GetValue(0);

And no more error.

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