You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MySQL .NET Connector新版本日期格式与项目设置不符问题咨询

问题描述

我在应用程序开头设置了线程区域格式:

System.Threading.Thread.CurrentThread.CurrentCulture=System.Globalization.CultureInfo.CreateSpecificCulture("es-DO") 
System.Globalization.DateTimeFormatInfo.CurrentInfo.ShortDatePattern = "dd'/'MM'/'yyyy"

将当前线程区域设置为es-DO,并指定短日期格式为dd/MM/yyyy。

同时通过以下代码从MySQL服务器获取日期:

Public Function BFecha_Servidor() As Boolean
    Using conn = ConexionADO.ObtenerConeccion()
        conn.Open()
        Dim MysqlCommand As New MySql.Data.MySqlClient.MySqlCommand("SELECT curdate()", conn)
        Fecha_Servidor = MysqlCommand.ExecuteScalar().ToString
    End Using
    Return True
End Function

使用MySQL .NET Connector 6.9.4版本时,获取的日期符合dd/MM/yyyy格式;但升级至8.0.30版本后,日期格式变为MM/dd/yyyy。我曾尝试修改服务器排序规则但未生效,目前打算尝试设置lc_time_names变量。

原因分析

MySQL Connector/NET 8.0版本在日期类型的处理逻辑上做了重大调整:

  • 6.x版本中,ExecuteScalar()返回的日期会直接按照客户端线程的CurrentCulture格式化字符串;而8.0版本则优先遵循MySQL会话的lc_time_names设置,当会话的区域设置与客户端线程不一致时,会使用服务器/会话的格式返回字符串。
  • 另外,8.0版本的Connector对日期类型的解析和序列化逻辑更严格,不再默认兼容旧版本的客户端格式化行为,而是更贴近MySQL服务器的原生处理规则。
解决方案

方案1:显式设置MySQL会话的lc_time_names

在每次连接打开后,先执行设置会话区域的SQL命令,确保日期格式与客户端一致:

Public Function BFecha_Servidor() As Boolean
    Using conn = ConexionADO.ObtenerConeccion()
        conn.Open()
        ' 设置会话的时间区域为多米尼加西班牙语
        Dim setLcCommand As New MySql.Data.MySqlClient.MySqlCommand("SET lc_time_names = 'es_DO'", conn)
        setLcCommand.ExecuteNonQuery()
        
        Dim MysqlCommand As New MySql.Data.MySqlClient.MySqlCommand("SELECT curdate()", conn)
        Fecha_Servidor = MysqlCommand.ExecuteScalar().ToString
    End Using
    Return True
End Function

也可以将该配置加入MySQL连接字符串,避免每次手动执行:

Server=xxx;Database=xxx;Uid=xxx;Pwd=xxx;Initial Statement=SET lc_time_names = 'es_DO';

方案2:手动控制日期格式化(更可靠)

不要依赖ExecuteScalar().ToString()的默认行为,将返回值转换为DateTime类型后,用指定格式输出:

Public Function BFecha_Servidor() As Boolean
    Using conn = ConexionADO.ObtenerConeccion()
        conn.Open()
        Dim MysqlCommand As New MySql.Data.MySqlClient.MySqlCommand("SELECT curdate()", conn)
        Dim serverDate As DateTime = Convert.ToDateTime(MysqlCommand.ExecuteScalar())
        ' 显式指定格式输出
        Fecha_Servidor = serverDate.ToString("dd/MM/yyyy")
    End Using
    Return True
End Function

这种方式完全脱离服务器和Connector的默认格式设置,直接由代码控制输出格式,兼容性最强。

方案3:兼容旧版本行为(不推荐)

如果需要临时兼容6.x版本的行为,可以在连接字符串中添加UseOldDateTimeBehavior=true,但该配置可能在未来版本中被移除,仅作为过渡方案使用。


内容的提问来源于stack exchange,提问作者EnmanuelP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 19:38:10