无法将MySQL日期/时间值转换为System.DateTime

问题描述 投票:75回答:9

我收到此错误:

无法将MySQL日期/时间值转换为System.DateTime

而我正在尝试从MySQL数据库中获取数据。我的MySQL数据库中有date数据类型。但是在将其检索到我的数据表中时,它会得到上面的错误。

我怎样才能解决这个问题?

.net asp.net mysql asp.net-3.5
9个回答
47
投票

如果我谷歌“无法将MySQL日期/时间值转换为System.DateTime”,我看到许多引用从Visual Studio访问MySQL的问题。这是你的背景吗?

一个解决方案建议:

这不是一个错误,而是预期的行为。请检查连接选项下的手动并将“允许零日期时间”设置为true,如附加图片所示,错误将消失。

参考:http://bugs.mysql.com/bug.php?id=26054


0
投票

在Stimulsoft报告中将此参数添加到连接字符串(右键单击datasource-> edit)

Convert Zero Datetime=True;

189
投票

您必须将Convert Zero Datetime=True添加到您的连接字符串,例如:

server=localhost;User Id=root;password=mautauaja;Persist Security Info=True;database=test;Convert Zero Datetime=True

19
投票

我添加了Convert Zero Datetime=TrueAllow Zero Datetime=True,它工作正常


3
投票

将日期时间值作为字符串向下拉并执行DateTime.ParseExact(value, "ddd MMM dd hh:mm:ss yyyy", culture, styles);您只需要为从数据库返回的日期设置日期格式。最有可能的是yyyy-MM-dd HH:mm:ss。至少对我而言。

点击这里查看有关DateTime.ParseExact的更多信息


2
投票

让MySql将你的unix时间戳转换为字符串。使用mysql函数FROM_UNIXTIME(113283901)


1
投票

我也遇到了同样的问题,并获得列名称及其类型。然后从表名转换(col_Name作为Char)。从这个方面我得到的问题是'0000-00-00 00:00:00'然后我更新作为有效的日期和时间错误离开我的情况。


1
投票

您可以使应用程序与MySql使用的日期和时间完全兼容。当应用程序在运行时运行时提供此代码。首先转到应用程序事件。在工具列表中

  1. 转到项目
  2. 项目属性
  3. 选择应用程序选项卡
  4. 查看应用事件

这将打开一个新文件。此文件包含在应用程序启动时使用的代码。

将此代码写入该新文件中:

 Partial Friend Class MyApplication

    Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup
        My.Application.ChangeCulture("en")
        My.Application.ChangeUICulture("en")
        My.Application.Culture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd"
        My.Application.Culture.DateTimeFormat.LongDatePattern = "yyyy-MM-dd"
        My.Application.Culture.DateTimeFormat.LongTimePattern = "HH:mm:ss"
        My.Application.Culture.DateTimeFormat.ShortTimePattern = "HH:mm:ss"
    End Sub


End Class

0
投票

您可以使用IsValidDateTime对象的MySqlDateTime属性来帮助您确定是否可以将对象强制转换为DateTime,而不是更改连接字符串。

我有一个场景,我试图从“UpdateTime”列加载数据,该列仅在行更新时显式设置(而不是始终设置的InsertedTime)。对于这种情况,我使用MySqlDataReader.GetMySqlDateTime方法,如下所示:

using (MySqlDataReader reader = await MySqlHelper.ExecuteReaderAsync(...))
{
    if (await reader.ReadAsync())
    {
        DateTime? updateTime = reader.GetMySqlDateTime("UpdateTime").IsValidDateTime ? (DateTime?)reader["UpdateTime"] : null;
    }
}

0
投票

如果“allow zero datetime = true”不起作用,请使用以下解决方案: -

将此添加到您的连接字符串:“allow zero datetime = no” - 这使得类型转换工作完美。

© www.soinside.com 2019 - 2024. All rights reserved.